MM2
MM2

Reputation: 649

insert `id` autoincrement primary key field explicitly in laravel 5.2

I am migrating an old data into laravel.

What i want is to keep the previous ids same in the new table where i have a default $table->increments(id) field.

Is there a way in laravel that i can explicitly insert this id field?

As i am unable to do it using eloquent model create method :

User::create([
'id' => 123456,
'first_name' => 'john',
'last_name' => 'doe'
])

Is it even possible in there?

Upvotes: 2

Views: 5918

Answers (1)

Sam
Sam

Reputation: 2658

The problem must be in the User model. Open the User.php file and modify the $fillable variable. Add id to the array. The $fillable variable tells Eloquent which fields to protect from a mass-assignment like the one you are doing (mass assignment meaning you're setting all the values at once in your insert). So even if you specify id like you did in your create() call Eloquent will ignore whatever value you have set because that field is not part of the $fillable fields.

So have that variable like:

protected $fillable = ['id', 'first_name', 'last_name'];

and you should be good to go (also taking into account that you have not left any fields empty which according to the user migration cannot be null)

Upvotes: 1

Related Questions