Set default to NULL with laravel migration
Asked Answered
L

3

82

I am adding a field to a table in a migration that I wish to allow to be NULL but also I wish for it to default to NULL. What do I place in the default method? I fear that putting "NULL" in will attempt to place a string of NULLin which I obviously don't want. Please help :)

Schema::table('item_categories', function(Blueprint $table)
{
    $table->integer('parent_item_category_id')->unsigned()->nullable()->default($what_to_put here);
});
Littrell answered 19/12, 2014 at 1:56 Comment(1)
Duplicated question with answers: https://mcmap.net/q/244449/-how-to-make-default-value-null-in-laravelUnconformity
L
185

When you use the nullable() method on a field, that field will default to NULL.

$table->integer('parent_item_category_id')->nullable();
Littrell answered 19/12, 2014 at 2:18 Comment(5)
If a field had a default value before and I try to apply a migration with the default value removed and the "nullable" method added, and then "change", it doesn't work. The default value from the first migration is kept. Just the "NOT NULL" definition gets removed. (With MySQL.)Pita
"When you use the nullable() method on a field, that field will default to NULL." Does no longer seem to be true for Laravel 5.3 when the strict DB mode is enabled and you use a timestamp. You have to explicitly set the default value to null.Visa
as an example : $table->string('email')->nullable();Brotherhood
Indeed as @JānisElmeris says, this won't work with change. I had to add a DB::statement() with a statement to alter the default to make this work.Glaser
Is nullable followed by default redundant? Should it just be default alone? eg: $table->boolean('share_location')->nullable()->default(0); OR $table->boolean('share_location')->default(0);Brigade
F
0

To make the column "nullable", you may use the nullable method:

$table->string('email')->nullable();
Fez answered 13/2, 2023 at 15:17 Comment(0)
V
0

Keep in mind that a nullable field is not the same as the field having null as the default value. In for instance MySQL the default value will however be null if not explicit set.

If a nullable field was original created with another default value, creating a new migration only by passing ->nullable() will not change the default value. In such a case the default value must be set using ->default(null).

Virtuosic answered 22/12, 2023 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.