Laravel 的注冊頁面只提供了 name
和 Email
, 有時(shí)需要增加自定義字段货邓。例如姓別四濒、地理位置等。Laravel 中可很容易的添加自定義字段戈二。
1. 生成數(shù)據(jù)遷移 (修改數(shù)據(jù)庫 table)
$ php artisan make:migration add_user_defined_field_to_users_table
修改數(shù)據(jù)數(shù)據(jù)遷移文件如下觉吭,我們添加了兩個(gè)自定義字段 pid
、role
台腥。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddUserDefinedFieldToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('pid', 20)->unique();
$table->string('role');
});
}
public function down()
{
//
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['pid', 'role']);
});
}
}
執(zhí)行 $php artisan migrate
绒北,使數(shù)據(jù)遷移生效。
2. 在Form中添加字段
修改 resources/auth/register.blade.php
加入以上兩個(gè)字段峻汉。如果想讓 role
不可見脐往,且默認(rèn)值為 customer
,html 可以這樣寫:
<input id="role" type="hidden" class="form-control" name="role" value="customer"
3. 修改 Controller
修改 app/Http/Controllers/Auth/RegisterController.php
的 validator
和 create
方法瘤礁。
protected function validator(array $data)
{
return Validator::make($data, [
'pid' => 'required|max:20',
'name' => 'required|max:255',
'role' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'pid' => $data['pid'],
'name' => $data['name'],
'email' => $data['email'],
'role' => $data['role'],
'password' => bcrypt($data['password']),
]);
}
4. 修改 Model
修改 app/User.php
protected $fillable = [
'pid', 'name', 'email', 'password', 'role',
];
打完收工柜思!