新用户注册应用程序时添加表单字段

Adding form fields when a new user registers with application

我正在尝试向 Laravel 5 创建的 users table 添加一个字段。我修改了迁移以添加该字段:

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->string('my_new_field'); // Added this field
            $table->rememberToken();
            $table->timestamps();
        });
    }
    ...    
}

我正在使用 Laravel 提供的默认身份验证系统。每当有新用户注册时,我都需要将 my_new_field 设置为某个值。我该怎么做(以及在哪里)?

AuthController 处理身份验证过程。它使用 trait AuthenticatesAndRegistersUsers,其中 postRegister() 函数处理注册请求。但是实际值在哪里插入?

只需将默认值添加到字段中即可:

class CreateUsersTable extends Migration {

    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->string('my_new_field')->default('init_value'); // Added this field
            $table->rememberToken();
            $table->timestamps();
        });
    }
    ...    
}

或者,如果已执行创建迁移,则只需使用新的迁移来添加列:

class AddMyNewFieldToUsersTable extends Migration {
    public function up()
    {
        Schema::table('users', function($table) {
            $table->string('my_new_field')->default('init_value'); // Added 
        });
    }

    public function down()
    {
        Schema::table('users', function($table) {
            $table->dropColumn('my_new_field');
        });
    }
}

如果您不想使用数据库默认值,您也可以在控制器中的 store 方法中设置此值:

public class UsersController extends BaseController {

    // ...

    public function store(Request $request) {
        $user = new User;
        $user->fill($request->all());
        $user->my_new_field = 'init_value';
        $user->save();

        // return whatever
    }
}

编辑 鉴于您在此处的评论中提供的信息,我们提供了一些指导:

AuthController (/app/Http/Controllers/Auth/AuthController.php) 中添加以下方法(这会覆盖 AuthenticatesAndRegistersUsers-trait 的默认值,可以在 here 中找到)

public function postRegister(Request $request)
{
    $validator = $this->validator($request->all());

    if ($validator->fails())
    {
        $this->throwValidationException(
            $request, $validator
        );
    }

    $user = $this->create($request->all()); // here the values are inserted
    $user->my_new_field = 'init_value';     // here would be the place to add your custom default
    $user->save();                          // maybe try to do all that in a single transaction...

    Auth::login($user);

    return redirect($this->redirectPath());
}

我不太确定这是否开箱即用,但它应该能让您入门。

App\Services\Registrar中的create()方法负责创建一个新的User实例。我将字段添加到此函数:

   /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    public function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'my_new_field' => 'Init Value'
        ]);
    }

根据 documentation

To modify the form fields that are required when a new user registers with your application, you may modify the App\Services\Registrar class. This class is responsible for validating and creating new users of your application.

The validator method of the Registrar contains the validation rules for new users of the application, while the create method of the Registrar is responsible for creating new User records in your database. You are free to modify each of these methods as you wish. The Registrar is called by the AuthController via the methods contained in the AuthenticatesAndRegistersUsers trait.

2016 年 2 月 3 日更新 Laravel 5.2 app/Services/Registrar.php 文件中的设置已移至 app/Http/Controllers/Auth/AuthController.php

我还必须在 User 模型中使该字段可填写:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
     ...
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'my_new_field'];
    ...
}

打开位于 (for Laravel 5.2 AuthController)

的特征
/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php

在这里您可以轻松找到负责登录和注册用户的有趣方法。

这些是

getRegister() // responsible for showing registration form

postRegister() // responsible for processing registration request

getLogin() // responsible for showing login form

postLogin() // responsible for authentication user

每次访问特定路由(auth/register 或 auth/login)时都会调用这些方法,即用户注册和用户登录

希望这会澄清一些概念!!