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

标签 php laravel laravel-5 eloquent

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

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() 函数处理注册请求。但是实际值在哪里插入?

最佳答案

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 日更新 拉维尔 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'];
    ...
}

关于php - 新用户注册应用程序时添加表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28957306/

相关文章:

php - 使用 php 和 xpath 在 html 标记后获取文本

php - 从使用 SQL 获取的数据中获取不同格式的数组

laravel - 需要安装 League/flysystem-aws-s3-v3 联盟/flysystem ^2.0 但卡在 1.1.3 时出现问题

php - 图像在数据库 laravel 中保存为 tmp 文件

php - 我如何创建一个 mysql_query 来提取使用贝叶斯平均值排名的项目?

php - symfony 中非共享服务的目的是什么?

wordpress - 从位于别处的目录访问特定的 Laravel 5 路由

php - Laravel 5.6 - 在 updateOrCreate 后获取更改的值

laravel - 如何使用 Laravel 从函数中的模型获取数据

php - Laravel html 表格