Search code examples
phplaravelpostgresqldatabase-migrationdbal

Successfully change column from nullable to set default, but the value is still null


I have table migration like this. I want to change the column from nullable to set default 0.

        Schema::create('table', function (Blueprint $table) {
            ...
            $table->integer('sold_count')->nullable();
            $table->integer('view_count')->nullable();
            ...
        });

But, when I am create migration to change the column from nullable to set default 0 like this. Why changed column is still null?

        Schema::table('table', function (Blueprint $table) {
            $table->integer('sold_count')->default(0)->change();
            $table->integer('view_count')->default(0)->change();
        });

How to fix this?


Solution

  • Setting a default does not remove the nullable from the column, this is how you would set a column as not nullable.

    Schema::table('table', function (Blueprint $table) {
        $table->integer('sold_count')->nullable(false)->default(0)->change();
        $table->integer('view_count')->nullable(false)->default(0)->change();
    });
    

    However this may not automatically set the default values to currently null columns because the default (as far as I know) applies to new inserts only. To fix this you could add this in your migration file before the Schema::table call:

    DB::table('table')->whereNull('sold_count')->update([ 'sold_count' => 0 ]);
    DB::table('table')->whereNull('view_count')->update([ 'view_count' => 0 ]);
    

    however this will result in your migration to not be fully reversible.