Problem Statement
Default values for timestamp columns in Laravel migrations utilizing the Schema Builder are set to '0000-00-00 00:00:00'; how do we modify this to 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'?
Solution
Utilize DB::raw() to incorporate CURRENT_TIMESTAMP as a column's default value:
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
Alternatively, after Laravel 5.1.25, you can use the useCurrent() method directly on the timestamp column:
$table->timestamp('created_at')->useCurrent();
For MySQL, include the ON UPDATE clause using DB::raw() or, from Laravel 8.36.0, the useCurrentOnUpdate() method:
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
Cautions
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP(0)'));
Thanks to @andrewhl for identifying the Laravel 4.x PostgreSQL issue, and @ChanakaKarunarathne for the useCurrentOnUpdate() shortcut.
The above is the detailed content of How Do I Populate Timestamp Columns with Current Timestamp Using Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!