How to add Default Value of Column in Laravel Migration?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Migration Custom Foreign Key Name Example
- How to Add Index in Laravel Migration?
- How to Add Foreign Key in Laravel Migration?
- Laravel Migration - How to Add New Column in Existing Table ?
- How to Change Table Name using Laravel Migration?
- How to Remove Column from Table in Laravel Migration?
- How to Change Column Name and Data Type in Laravel Migration?
- How to Create Table using Migration in Laravel?
- How to Drop Foreign Key Constraint in Laravel Migration?
- How to Add MySQL Trigger from Migration in Laravel?