Laravel migrations change default value of column

Brendan Van Der Merwe picture Brendan Van Der Merwe · May 3, 2016 · Viewed 41k times · Source

I have a table with a default value already assigned. For an example we can look at the following:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->integer('active')->default(1);
        });

I now want to change my default value on the active field. I am expecting to do something like this:

if (Schema::hasTable('users')) {
        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'active')) {
                $table->integer('active')->default(0);
            }
        });
    }

But of course it tells me the column is already there. How can I simply update the default value of column x without dropping the column?

Answer

Alexey Mezenin picture Alexey Mezenin · May 3, 2016

You can use change() method:

Schema::table('users', function ($table) {
    $table->integer('active')->default(0)->change();
});

Then run migrate command.

Update

For Laravel 4 use something like this:

DB::statement('ALTER TABLE `users` CHANGE COLUMN `active` `active` INTEGER NOT NULL DEFAULT 0;');

Inside up() method instead of Schema::table(); clause.