Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-20 12:28:30
Original
1079 people have browsed it

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'));
Copy after login

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

$table->timestamp('created_at')->useCurrent();
Copy after login

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();
Copy after login

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)'));
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template