Home >Backend Development >PHP Tutorial >How Do I Set the Default Value of Timestamp Columns to CURRENT_TIMESTAMP and Auto Update in Laravel Migrations?
Setting Default Value of Timestamp Column to Current Timestamp in Laravel Migrations
Question: How can I create a timestamp column with a default value of CURRENT_TIMESTAMP and update it to CURRENT_TIMESTAMP in Laravel migrations?
Laravel's Schema Builder does not explicitly provide a method to set the default value of a timestamp column to CURRENT_TIMESTAMP.
Answer:
To set the default value to CURRENT_TIMESTAMP, use the DB::raw() method to define a raw expression:
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
For MySQL, you can additionally use the ON UPDATE clause within DB::raw():
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
As of Laravel 5.1.25, you can use the useCurrent() method to simplify this:
$table->timestamp('created_at')->useCurrent();
In Laravel 8.36.0 and above, useCurrent() can be used with the useCurrentOnUpdate() method for both default and on-update values:
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
Gotchas:
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP(0)'));
The above is the detailed content of How Do I Set the Default Value of Timestamp Columns to CURRENT_TIMESTAMP and Auto Update in Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!