Home >Backend Development >PHP Tutorial >How Do I Set the Default Timestamp to the Current Timestamp in Laravel Migrations?
In Laravel, timestamps are commonly used to track activity, such as when a record was created or updated. By default, these timestamps are set to 0000-00-00 00:00. However, it can be useful to automatically set the default value to the current timestamp.
For timestamps that you want to update regularly, you can use the DB::raw() function to specify CURRENT_TIMESTAMP as the default value:
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
This ensures that the created_at column will always contain the current timestamp, both when the record is initially created and when it is updated.
Alternatively, you can use the useCurrent() or useCurrentOnUpdate() methods to achieve the same result:
$table->timestamp('created_at')->useCurrent(); $table->timestamp('updated_at')->useCurrentOnUpdate();
The useCurrent() method assigns the current timestamp as the default value for both creation and updates, while useCurrentOnUpdate() sets the default value for updates only.
For MySQL, you can use the ON UPDATE clause within DB::raw():
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
The above is the detailed content of How Do I Set the Default Timestamp to the Current Timestamp in Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!