In this post, you will learn, how to set the default value NULL
in laravel migration.
Many times we need to get the default value of the column to be NULL while creating the model using laravel migration. By completing this article you will be able to set the default value of column NULL in laravel migration.
This tutorial works for all types of laravel versions including laravel 6, laravel 7, laravel 8 and laravel 9 as well.
Let’s get Started
Table of Contents
Step 1: Create Migration File
Let’s create the migration file first. I am creating a migration for creating articles
table. Type the following command in the terminal:
php artisan make:migration create_articles_table
This will create a migration file in the database/migrations
the folder which will look like this:
<?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('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
Step 2: Add the Column to have Default Value NULL in create function
In the above code, create
the function is responsible for creating columns of the table. So will edit that and we will add the title
column which will have default value NULL
.
Add the following code to the create
function:
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title')->nullable();
});
So in the above code, we added title
string and set it to be NULL by using nullable(). By using nullable() it will automatically set the default value to NULL. Thats it 🙂
Conclusion
In the above article, hope you have learned how to set the default value to NULL in laravel migration.
Let me know if you have questions. I will see you the next one.
Write a Reply or Comment