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
Linda HamiltonOriginal
2024-12-03 02:44:14240browse

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'));

Using useCurrent() (Laravel 5.1.25 ):

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

For MySQL only:

Using DB::raw() with ON UPDATE:

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

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

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

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!

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