PASSWORD RESET

Your destination for complete Tech news

How to make a column nullable in Laravel migration?

3.32K 0
< 1 min read

To make a column nullable in a migration file in Laravel, you can use the nullable method on the column definition.

Here’s an example of how you can use the nullable method to make the email column nullable:

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

class AddEmailToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('email')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('email');
        });
    }
}

You can then run the migration using the php artisan migrate command.

Alternatively, you can also use the change method to modify an existing column and make it nullable. Here’s an example:

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

class MakeEmailNullableInUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('email')->nullable()->change();
        });
    }

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

Again, you can run this migration using the php artisan migrate command.

Remember, to change the column you need to have a doctrine/dbal dependency.

composer require doctrine/dbal

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.