Laravel migrations change default value of column

PhpLaravelMigrationLaravel Artisan

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

You have to call the change function to update the column

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

Solution 3 - Php

Create new migration file. and use change()

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

And also be sure to add the doctrine/dbal dependency to your composer.json file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrendan Van Der MerweView Question on Stackoverflow
Solution 1 - PhpAlexey MezeninView Answer on Stackoverflow
Solution 2 - PhpJerodevView Answer on Stackoverflow
Solution 3 - PhpYasin PatelView Answer on Stackoverflow