How To Add Default Value of Column in Laravel Migration?

Laravel 8 , Laravel 7 , Laravel , Laravel 6

Nicesnippets

3966

29-05-2021


Hello Friends,

In this blog, i would like to share with you how to add default value of column in laravel migration. We will talk about laravel migration in set defaule value of column. if you want to set default value of table column using migration in laravel.

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 and laravel 8 version

Here i will give you easy and simple way to set default value of table column using migration in laravel.so let's see bellow simple examples:

Create Migration Command:


php artisan make:migration create_products_table

database/migrations/2021_05_29_295911_create_products_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->id();

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

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

$table->decimal('price',8,2)->default(0);

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

$table->enum('deleted',[1,2])->default(1);

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('products');

}

}

1) Laravel Migration Default Value Null:

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

2) Laravel Migration Default Value Boolean:

$table->boolean('is_active')->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('status')->default(0)->change();

It will help you....


Recommended Posts