In this tutorial you will learn about the How To Add Default Value of Column in Laravel Migration and its application with practical example.
In this article, I’ll show you how to add default column value in laravel migration. You will learn learn to set defaule value of column while creating table using laravel migration.
How To Add Default Value of Column in Laravel Migration
Laravel migration provide default() and nullable() method to set default value of a column. In this example we will learn how to add default value as null, boolean, current time etc. In this step by step we will set default value of table column using migration in laravel.
Create Table Migration
Use the following artisan command to create table migration:
1 |
php artisan make:migration create_products_table |
After the command executed you will notice a migration file created. Open migration file and put the following code in it:
database/migrations/YYYY_MM_DD_TIMESTAMP_create_products_table.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?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:
1 |
$table->string('name')->nullable(); |
2) Laravel Migration Default Value Boolean:
1 |
$table->boolean('is_active')->default(0); |
3) Laravel Migration Default Value Current Date:
1 |
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); |
4) Laravel Migration Default Value with Update:
1 |
$table->boolean('status')->default(0)->change(); |