Home > Database > Mysql Tutorial > How to Set Default Timestamp Columns to CURRENT_TIMESTAMP in Laravel Migrations?

How to Set Default Timestamp Columns to CURRENT_TIMESTAMP in Laravel Migrations?

DDD
Release: 2024-11-22 08:14:15
Original
779 people have browsed it

How to Set Default Timestamp Columns to CURRENT_TIMESTAMP in Laravel Migrations?

Laravel: Setting Default Timestamp Columns to the Current Timestamp

Problem:

In Laravel's Schema Builder/Migrations, users seek guidance on how to create a timestamp column with a default value of CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP. The timestamps() function currently defaults to 0000-00-00 00:00 for both created and updated columns.

Solution:

To set the default value of a timestamp column to CURRENT_TIMESTAMP using Laravel migrations, use DB::raw():

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

Since Laravel 5.1.25, you can simplify this using the useCurrent() column modifier:

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

For MySQL, ON UPDATE CURRENT_TIMESTAMP can be used via DB::raw():

$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
Copy after login

Starting with Laravel 8.36.0, useCurrent() and useCurrentOnUpdate() together can achieve the same:

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

Gotchas:

  • MySQL: Prior to 5.7, 0000-00-00 00:00:00 was invalid. Use useCurrent() or nullable() to resolve this.
  • PostgreSQL & Laravel 4.x: The default precision for timestamp columns caused problems with Carbon parsing. Use DB::raw('CURRENT_TIMESTAMP(0)') to ensure zero precision.
  • PostgreSQL & Laravel 5.0 : The default precision is now zero, preventing this issue.

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

The above is the detailed content of How to Set Default Timestamp Columns to CURRENT_TIMESTAMP in Laravel Migrations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template