Home > Database > Mysql Tutorial > How to Set a Timestamp Column\'s Default Value to CURRENT_TIMESTAMP in Laravel Migrations?

How to Set a Timestamp Column\'s Default Value to CURRENT_TIMESTAMP in Laravel Migrations?

Linda Hamilton
Release: 2024-12-03 02:44:14
Original
284 people have browsed it

How to Set a Timestamp Column's Default Value to CURRENT_TIMESTAMP in Laravel Migrations?

Setting Timestamp Column Default Value to Current Timestamp with Laravel Migrations

Question:

How can I create a timestamp column with a default value of CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP using Laravel Schema Builder/Migrations?

Answer:

Using DB::raw() (all databases):

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

Using useCurrent() (Laravel 5.1.25 ):

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

For MySQL only:

Using DB::raw() with ON UPDATE:

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

Using useCurrent() and useCurrentOnUpdate() (Laravel 8.36.0 ):

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

Gotchas:

  • MySQL:

    • Starting with MySQL 5.7, 0000-00-00 00:00:00 is not a valid date. Default timestamp columns to current timestamps using useCurrent(), or make them nullable.
  • PostgreSQL & Laravel 4.x:

    • Explicitly specify a precision of zero to CURRENT_TIMESTAMP to avoid parsing errors. (Since Laravel 5.0, precision is set to zero by default.)

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