How to Add Nullable to an Existing Column in Laravel

Article author Jelle de Vries
Jelle de Vries
September 12, 2022 (Updated September 13, 2022)

When working with Laravel migrations, you might come across the following situation: you create a new table, but you forget to add nullable to your column. Later, you come across a situation where you actually want to insert a null value. But how do you add nullable to your database column through a Laravel migration?

You can achieve this creating a new migration (by using php artisan make:migration or manually creating a migration), and using the following strategy:

public function up()
{
    Schema::table('products', function (Blueprint $table) {
        $table->string('name')->nullable(true)->change();
    });
}

public function down()
{
    Schema::table('products', function (Blueprint $table) {
        $table->string('name')->nullable(false)->change();
    });
}

Now run your migration by executing:

php artisan migrate

The great thing about this strategy is that it also allows for rolling back your migration. Simply run:

php artisan migrate:rollback

The code sample above works with your Laravel Eloquent models, as well as tables without a model that you want to alter through your migration.

Comments