Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel migrations change default value of column

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?

like image 262
Brendan Van Der Merwe Avatar asked May 03 '16 11:05

Brendan Van Der Merwe


People also ask

What is foreign key in laravel migration?

Foreign Keys Laravel also provides support for adding foreign key constraints to your tables: $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); In this example, we are stating that the user_id column references the id column on the users table.

How do I set the default time in laravel?

This is how you do it, I have checked it and it works on my Laravel 4.2. $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); Hope this helps.


2 Answers

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.

like image 86
Alexey Mezenin Avatar answered Oct 02 '22 16:10

Alexey Mezenin


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();         }     }); } 
like image 20
Jerodev Avatar answered Oct 02 '22 17:10

Jerodev