Laravel migration default value

Laravel migration default value

How to set default value in Laravel migration? or how to set column to be nullable? what about changing from certain column to a nullable one?

How to set default value in Laravel migration

We might run to cases where we need to set a default value to a column in Laravel migration.

this are some use cases that can inspire you to work on your Laravel application

Default value null (nullable)

First default we might need is a nullable column, which sets it to null on creation.

$table->string('title')->nullable();

Default value a string

Then other times we want to set a default value, that is a string. but this column would never be null.

$table->string('title')->default('the default value');

Default string with a nullable column

If we need a default nullable column, but we provide a value on creation.

$table->string('title')->nullable('the default value');

Default expression

Sometimes we want to set a value to a default json value, so we need to unwrap it from the quotes. Therefor we can use Illuminate\Database\Query\Expression.

Laravel documentation provides the example new Expression('(JSON_ARRAY())')

$table->json('movies')->default(new Expression('(JSON_ARRAY())'));

This can be a string or an array or anything, with Helpers in Laravel

$table->string('title')->default(STR::plural('some value')));
$table->string('title')->default(Str::between('This', 'that', 'other'))));

Default current timestamp

If we need time current time, to be the default of a column name, we can use

$table->timestamp('published_time')->useCurrent();

Default current timestamp when we update

$table->timestamp('published_time')->useCurrent()->useCurrentOnUpdate();

Default value to existing column

If we already created a column name, but we want to give it a default value, we can using the change method.

$table->string('title');
// we can change it to accept a default value
$table->string('title')->default('the default value')->change();