65

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?

  • well since its only about one column you can do it manually by using interface like phpmyadmin(xampp), workbench etc. so you will not loose any data.. – Manoj Salvi May 03 '16 at 12:58
  • Thats what I have done for now to fix it on our live server but I would still like to know whats the best way moving forward. Otherwise I was also thinking of just upgrading to laravel 5 – Brendan Van Der Merwe May 03 '16 at 13:02
  • here is a link that might help you - http://www.flipflops.org/2013/05/25/modify-an-existing-database-column-in-a-laravel-migration/ – Manoj Salvi May 03 '16 at 13:05
  • Seems like a raw query inside my migration script is the way to go here. Really thought I was missing something obvious here. – Brendan Van Der Merwe May 03 '16 at 13:19
  • yes it could work both the ways - by writing the alter query inside existing migration or inside a newly created migration.. – Manoj Salvi May 03 '16 at 13:22

3 Answers3

112

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.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
6

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();
        }
    });
}
Jerodev
  • 32,252
  • 11
  • 87
  • 108
-2

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

Yasin Patel
  • 5,624
  • 8
  • 31
  • 53
  • `refresh` will not change the default value of anything, you're just resetting everything, – Salam Nov 25 '19 at 10:53