Home  >  Article  >  Backend Development  >  How Do I Populate Timestamp Columns with Current Timestamp Using Laravel Migrations?

How Do I Populate Timestamp Columns with Current Timestamp Using Laravel Migrations?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 12:28:30961browse

How Do I Populate Timestamp Columns with Current Timestamp Using Laravel Migrations?

How to Populate Timestamp Columns with Current Timestamp Using Laravel Migrations

Problem Statement

Default values for timestamp columns in Laravel migrations utilizing the Schema Builder are set to '0000-00-00 00:00:00'; how do we modify this to 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'?

Solution

Utilize DB::raw() to incorporate CURRENT_TIMESTAMP as a column's default value:

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

Alternatively, after Laravel 5.1.25, you can use the useCurrent() method directly on the timestamp column:

$table->timestamp('created_at')->useCurrent();

For MySQL, include the ON UPDATE clause using DB::raw() or, from Laravel 8.36.0, the useCurrentOnUpdate() method:

$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();

Cautions

  • MySQL (version 5.7 onwards): '0000-00-00 00:00:00' is no longer valid. Hence, provide a valid default (e.g., useCurrent() or nullable()) for timestamp columns.
  • PostgreSQL (Laravel 4.x): Ensure to specify zero precision for CURRENT_TIMESTAMP to prevent timestamp parsing errors due to fractional seconds:
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP(0)'));

Thanks to @andrewhl for identifying the Laravel 4.x PostgreSQL issue, and @ChanakaKarunarathne for the useCurrentOnUpdate() shortcut.

The above is the detailed content of How Do I Populate Timestamp Columns with Current Timestamp Using 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