19

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.

1 Answer 1

53

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you use $table->timestamp('last_activity')->useCurrent(); it'd continue to set last_activity whenever the row is updated.
Am I somehow missing the obvious here? This code fails if you have at least one row in users! You'll need to first create the column nullably, then set the defaults, and then disable the nullability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.