Problem:
In Laravel's Schema Builder/Migrations, users seek guidance on how to create a timestamp column with a default value of CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP. The timestamps() function currently defaults to 0000-00-00 00:00 for both created and updated columns.
Solution:
To set the default value of a timestamp column to CURRENT_TIMESTAMP using Laravel migrations, use DB::raw():
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
Since Laravel 5.1.25, you can simplify this using the useCurrent() column modifier:
$table->timestamp('created_at')->useCurrent();
For MySQL, ON UPDATE CURRENT_TIMESTAMP can be used via DB::raw():
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
Starting with Laravel 8.36.0, useCurrent() and useCurrentOnUpdate() together can achieve the same:
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
Gotchas:
Thanks to @andrewhl for the Laravel 4.x issue and @ChanakaKarunarathne for the useCurrentOnUpdate() shortcut.
The above is the detailed content of How to Set Default Timestamp Columns to CURRENT_TIMESTAMP in Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!