Itzhak Avraham Itzhak Avraham - 7 months ago 82
PHP Question

Laravel 5.2 - Insert value into User column not working

I created a simple user registration application:

$confirmation_key = str_random(100);
$data = [
'email' => $post['email'],
'password' => Crypt::encrypt($post['password']),
'confirmation_key' => $confirmation_key
];
User::create($data);


Of course I added a migration for it:

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('confirmed')->default(0);
$table->string('confirmation_key')->nullable();
$table->rememberToken();
$table->timestamps();
});
}


The user added successfully into the database, but the confirmation key still null, not changing.
Additional question: What if i want to add another columns to User table? What i need to do?

Answer

You need to make sure you have added confirmation_key into $fillable property of User model like so:

protected $fillable = ['email','password','confirmation_key'];

If you want to add another columns you need to create new migration and run it and if you want to make this column fillable you need to add it to $fillable property of User model.

EDIT

If you want to make any column not fillable using create of fill method you can add it into table and it won't be possible simply to do:

User::create($data);

in those cases you will need something like this:

// here you fill fillable data
$user = new User($data);
// this way you can fill properties that are not fillable
$user->some_not_fillable_property = 'some value';
// now you save it to database
$user->save();
Comments