Home >Database >Mysql Tutorial >How to Set Default Timestamps and Auto-Update Timestamps in Laravel Migrations?

How to Set Default Timestamps and Auto-Update Timestamps in Laravel Migrations?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 20:38:13989browse

How to Set Default Timestamps and Auto-Update Timestamps in Laravel Migrations?

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:

  • useCurrent() (available from Laravel 5.1.25): Simplifies the default value setting to the current timestamp, replacing DB::raw('CURRENT_TIMESTAMP').
$table->timestamp('created_at')->useCurrent();
  • useCurrentOnUpdate() (available from Laravel 8.36.0): Adds the ability to update the timestamp upon value change alongside 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 default precision of timestamp columns can lead to unexpected behavior.
  • Use CURRENT_TIMESTAMP(0) or update to Laravel 5.0 to use a default precision of zero and avoid these issues.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn