How to add Default Value of Column in Laravel Migration?

By Hardik Savani April 16, 2024 Category : Laravel

Hi,

Now, let's see tutorial of add default value in laravel migration. This article goes in detailed on default value in laravel migration. this example will help you laravel migration set default value null. We will use set default value in laravel migration.

laravel migration provide default() and nullable() where you can set default value of that column. here i will give you simple examples how to add default value as null, boolean, current time etc. you can easily set with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

so let's see bellow simple examples:

Create Migration Command:

php artisan make:migration create_items_table

database/migrations/2021_04_07_125911_create_items_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateItemsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('items', function (Blueprint $table) {

$table->id();

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

$table->text('body')->default('NO BODY');

$table->boolean('is_active')->default(0);

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('items');

}

}

1) Laravel Migration Default Value Null:

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

2) Laravel Migration Default Value Boolean:

$table->boolean('displayed')->default(0);

3) Laravel Migration Default Value Current Date:

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

4) Laravel Migration Default Value with Update:

$table->boolean('displayed')->default(0)->change();

you can use as you need.

i hope it can help you...

Tags :
Shares