Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Migration: Add a column with a default value of an existing column

i need to add a last_activity column on a table of a live site where i have to make it's default value to equal of updated_at column value. I'm using laravel 5.1 and mysql database driver.

Schema::table('users', function(Blueprint $table)
{
    $table->dateTime('last_activity')->default("COLUMN VALUE OF UPDATED_AT");
});

Thanks.

like image 230
Parvez Rahaman Avatar asked May 12 '16 10:05

Parvez Rahaman


1 Answers

This should work:

Schema::table('users', function(Blueprint $table) {
    $table->dateTime('last_activity');
});

\DB::statement('UPDATE users SET last_activity = updated_at');

See "Running a General Statement": https://laravel.com/docs/5.1/database#database-transactions

To enforce this relationship when a User is created or updated, you can use Model Events and/or Model Observers.

like image 107
tptcat Avatar answered Oct 09 '22 15:10

tptcat