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

How to Set Default Timestamp Values in Laravel Migrations?

Mary-Kate Olsen
Release: 2024-11-22 14:59:13
Original
878 people have browsed it

How to Set Default Timestamp Values in Laravel Migrations?

Setting Default Timestamp Values Using Laravel Migrations

The Laravel Schema Builder provides a convenient way to create and modify database tables. However, users occasionally encounter issues in setting default timestamp values to the current timestamp upon creation and updating.

The timestamps() Method

Typically, the timestamps() method is used to automatically manage the created_at and updated_at timestamp columns. However, this method sets their default values to '0000-00-00 00:00:00'.

Solution: DB::raw() and useCurrent()

To set a default value of CURRENT_TIMESTAMP, use DB::raw():

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

As of Laravel 5.1.25, you can also use the useCurrent() method:

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

MySQL ON UPDATE Clause

For MySQL, you can specify the ON UPDATE clause using DB::raw():

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

As of Laravel 8.36.0, you can use useCurrentOnUpdate() in conjunction with useCurrent():

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

Gotchas

  • MySQL: Since MySQL 5.7, '0000-00-00 00:00:00' is invalid. Use useCurrent() or make timestamps nullable.
  • PostgreSQL & Laravel 4.x: Use CURRENT_TIMESTAMP(0) to ensure zero precision and avoid Carbon parsing issues.

The above is the detailed content of How to Set Default Timestamp Values 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template