How to make a column NOT NULL or NULL in Laravel migration

Laravel migrations are a great way to keep your App’s database in synch with your application code. You can use Laravel migrations to create or update table definitions and columns. In this simple tutorial I am going to show you how to make a column NOT NULL or NULL by default in a Laravel laravel Migration. For example, you created a table column with default NULL but later you want to make it default NOT NULL

How to make a column NOT NULL or NULL in Laravel migration

In this example, the name of our database table is courses and name of column in courses table is is_demo

Let’s start with creating a new migration

php artisan make:migration change_is_demo_field_in_courses_table

Now open this migration file name of which ends with change_is_demo_field_in_courses_table.php and is located in database/migrations.

In this file, change the up() function content to:

Schema::table('courses', function (Blueprint $table) {
    $table->boolean('is_demo')->nullable(true)->default(0)->change();
});

And in the down() function change it to:

Schema::table('courses', function (Blueprint $table) {
    $table->boolean('is_demo')->nullable(false)->default(null)->change();
});

Run Migration to Make a Column NOT NULL

Now when you run your migration next time with php artisan migrate the is_demo column should be changed to NULL default 0.

In order to revert back, run php artisan migrate:rollback after you have run the above command and it should revert back column to its previous state.

I hope this small tutorial to make a column NOT NULL or NULL in Laravel migration helps you with your next Laravel Project.

Have Laravel Project in mind? Contact me.

Leave a Reply