Setting Current Timestamps as Default for Timestamp Columns in Laravel Migrations
Q: How can I configure a timestamp column in Laravel Migrations to default to the current timestamp with the option to update itself upon value change?
A: Laravel's Schema Builder provides a simple method to achieve this:
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
DB::raw is used to create a raw expression, allowing us to set CURRENT_TIMESTAMP as the default. This solution works effectively across various database drivers.
Enhancements in Laravel:
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
Cautions:
MySQL (5.7 and above):
Ensure to assign a valid default value to timestamp columns to avoid potential issues with invalid dates (e.g., 0000-00-00 00:00:00). Use useCurrent() or make the columns nullable.
PostgreSQL with Laravel 4.x:
The above is the detailed content of How to Set Default Timestamps and Auto-Update Timestamps in Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!