Written by me@grafxflow
06 Aug, 2024
0
538
When we create a Laravel migration and are using nullable() - everything should be fine by default which is true of most instances. But what about creating a foreign key migration and using a short syntax such as constrained() and we want to make that nullable.
On the face of it both syntax examples below should work? Yes or No?
// Answer A:
$table->foreignId('post_id')->nullable()->constrained();
or....
// Answer B:
$table->foreignId('post_id')->constrained()->nullable();
Unfortunately No is the answer. Below is the wrong combination order.
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('post_id')->constrained()->nullable(); // WRONG!
$table->timestamps();
});
So what would happen if you were to run this migration. Well actually there would be no errors at all and in the terminal it would seem to have worked perfectly as expected.
But afterwards when creating an insert such as below.
Tag::create(['name' => 'Category']);
It would flag up the following error.
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]:
General error: 1364 Field 'post_id' doesn't have a default value
(SQL: insert into `tags` (`name`, `updated_at`, `created_at`)
values (Category, 2024-08-06 11:40:00, 2024-08-06 11:40:00))'
The official Laravel documentation does give the following info.
Any additional column modifiers must be called before the constrained method:
So nullable() is one of those column modifiers therefore the correct option is to add it before constrained() as below.
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('post_id')->nullable()->constrained(); // WORKS
$table->timestamps();
});
So best to be aware of this in advance and don't get caught out as I did!
->nullable()->constrained(); and NOT ->constrained()->nullable();
Hope this helps!
07 Oct, 2016
26 Apr, 2018
13 Dec, 2016
I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!
Follow11 Jul, 2023
21 Jun, 2023
Views: 165,963
Views: 40,147
Views: 36,850
Views: 33,460