ItSolutionStuff.com

How to add Default Value of Column in Laravel Migration?

By Hardik Savani • April 16, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Migration Custom Foreign Key Name Example

Read Now →

How to Add Index in Laravel Migration?

Read Now →

How to Add Foreign Key in Laravel Migration?

Read Now →

Laravel Migration - How to Add New Column in Existing Table ?

Read Now →

How to Change Table Name using Laravel Migration?

Read Now →

How to Remove Column from Table in Laravel Migration?

Read Now →

How to Change Column Name and Data Type in Laravel Migration?

Read Now →

How to Create Table using Migration in Laravel?

Read Now →

How to Drop Foreign Key Constraint in Laravel Migration?

Read Now →

How to Add MySQL Trigger from Migration in Laravel?

Read Now →