Spread the love

Default value to column is useful when we want to auto fill the default defined value of column during insertion of other values of table So In our this article i will show you to add default value to column in laravel migration. We can add any type of data type and configuration to table and column using laravel migration therefore we also want to add default value to column so its inserted by predefined value if it not defined by the user or system.

In this post we will take a simple example in which we will create a table and column with default value. this example will work all version of laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

creating default value field using default method of laravel Schema class and it accepts one parameters as the value.

Here is the syntax

$table->string('status')->default("APPROVE");

We will use the php artisan command to generate the Add Default Value to Column in Laravel migration and php artisan migrate command to modify the table.

Let’s understand it step by step

Step 1 : Generate migration file

To generate the migration file we will use the laravel artisan command so open the terminal in project and run below command

php artisan make:migration movies_table

Above command will create a migration file in folder database/migrations

Output: 
Created Migration: 2022_06_30_174050_movies_table

Step 2 : Open generated migration file and update

In the last step we created a migration file using the artisan command and now we wanted to add a column to the table so adding a status column as string with default value.

so let’s open the file and start editing

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMoviesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();
            $table->int('user_id');
            $table->string('title');
            $table->string('body')->nullable();
            $table->string('status')->default("APPROVE");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
         Schema::dropIfExists('movies');
    }
}

as you can see we have created string field using $table->string('status')->default("APPROVE"); syntax.

Step 3 : Run Migration

In this step we will execute our migration in database using below command

php artisan migrate

This will create table in database and the output

Output: 
Migrating: 2022_02_15_174050_movies_table
Migrated:  2022_02_15_174050_movies_table (20.08ms)

Also Read : How to rollback a specific migration in laravel ?

Leave a Reply