Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading