Laravel 5.4 注册表单加入自定义字段

参考链接:http://www.easylaravelbook.com/blog/2015/09/25/adding-custom-fields-to-a-laravel-5-registration-form/

Laravel 的注册页面只提供了 nameEmail, 有时需要增加自定义字段。例如姓别、地理位置等。Laravel 中可很容易的添加自定义字段。

1. 生成数据迁移 (修改数据库 table)

$ php artisan make:migration add_user_defined_field_to_users_table

修改数据数据迁移文件如下,我们添加了两个自定义字段 pidrole

<?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']);
        });
    }
}

执行 $php artisan migrate,使数据迁移生效。

2. 在Form中添加字段

修改 resources/auth/register.blade.php 加入以上两个字段。如果想让 role 不可见,且默认值为 customer,html 可以这样写:

<input id="role" type="hidden" class="form-control" name="role" value="customer"

3. 修改 Controller

修改 app/Http/Controllers/Auth/RegisterController.phpvalidatorcreate 方法。

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',
    ];

打完收工!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容