I'll-Be-Back
I'll-Be-Back

Reputation: 10828

remove Default in migration?

In the migration I alter enabled field to set to 1 value as default.

public function up()
{
    Schema::table('client', function (Blueprint $table) {
        $table->boolean('enabled')->default(1)->change();
    });
}

In down() method - How do I remove default() ? I know can do default(0) but default was never created during create table.

Upvotes: 56

Views: 27618

Answers (2)

Julian Rodriguez
Julian Rodriguez

Reputation: 574

Since there is no way to remove this statement with Laravel functions, your down function must execute the statement as raw. It should be something like:

public function down()
{
    DB::statement('ALTER TABLE client ALTER COLUMN enabled DROP DEFAULT');
}

In order to execute this migration, you need to include at the top of your migration:

use Illuminate\Support\Facades\DB;

Upvotes: 12

x-yuri
x-yuri

Reputation: 18863

Surprisingly or not, for NOT NULL fields ->default(null) removes the default from a table:

public function up()
{
    Schema::table('client', function (Blueprint $table) {
        $table->boolean('enabled')->default(null)->change();
    });
}

Just omitting the default() part doesn't work, since laravel makes a diff between current state and current state + specified changes. No changes specified, no diff.

After that, doctrine generates ALTER TABLE statement, treating NULL as no default value.

With nullable fields though, from what I can see, doctrine doesn't let you simply drop the default. The only option is supposedly to make them NOT NULL:

public function up()
{
    Schema::table('client', function (Blueprint $table) {
        $table->boolean('enabled')->nullable(false)->default(null)->change();
    });
}

Maybe with PostgreSQL you can get away without converting to NOT NULL, but that's to be confirmed.

Upvotes: 91

Related Questions