I'm trying to add a field to the users table created by Laravel 5. I've modified the migration to add that field:
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();
});
}
...
}
I'm using the default authentication system provided by Laravel. Whenever a new user registers, I need my_new_field to be set to some value. How (and where) do I do that?
The AuthController handles the authentication process. It uses the trait AuthenticatesAndRegistersUsers where the postRegister() function handles the registration requests. But where are the actual values inserted?
The create() method in App\Services\Registrar is responsible for creating a new User instance. I added the field to this function:
/**
* 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'
]);
}
According to the documentation,
To modify the form fields that are required when a new user registers with your application, you may modify the
App\Services\Registrarclass. This class is responsible for validating and creating new users of your application.The
validatormethod of the Registrar contains the validation rules for new users of the application, while thecreatemethod 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 theAuthControllervia the methods contained in theAuthenticatesAndRegistersUserstrait.
UPDATE Feb 03, 2016 Laravel 5.2 The settings found in the app/Services/Registrar.php file have been moved to app/Http/Controllers/Auth/AuthController.php
I also had to make this field fillable in the User model:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
...
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password', 'my_new_field'];
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With