Home >Database >Mysql Tutorial >How to Set Default Timestamp Values in Laravel Migrations?
Setting Default Timestamp Values Using Laravel Migrations
The Laravel Schema Builder provides a convenient way to create and modify database tables. However, users occasionally encounter issues in setting default timestamp values to the current timestamp upon creation and updating.
The timestamps() Method
Typically, the timestamps() method is used to automatically manage the created_at and updated_at timestamp columns. However, this method sets their default values to '0000-00-00 00:00:00'.
Solution: DB::raw() and useCurrent()
To set a default value of CURRENT_TIMESTAMP, use DB::raw():
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
As of Laravel 5.1.25, you can also use the useCurrent() method:
$table->timestamp('created_at')->useCurrent();
MySQL ON UPDATE Clause
For MySQL, you can specify the ON UPDATE clause using DB::raw():
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
As of Laravel 8.36.0, you can use useCurrentOnUpdate() in conjunction with useCurrent():
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
Gotchas
The above is the detailed content of How to Set Default Timestamp Values in Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!