Home  >  Article  >  Backend Development  >  How to Set Laravel Timestamps to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP?

How to Set Laravel Timestamps to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP?

DDD
DDDOriginal
2024-10-20 12:17:02249browse

How to Set Laravel Timestamps to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP?

Default Timestamp with Laravel Migrations

Laravel's Schema Builder simplifies database schema manipulation, but setting the default value of a timestamp column to the current timestamp can be a challenge.

Problem:

In Laravel, timestamps() generates timestamp columns with a default value of 0000-00-00 00:00. How can we set this default to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP using Laravel migrations?

Solution:

To specify CURRENT_TIMESTAMP as the default value for a timestamp column, use DB::raw():

<code class="php">$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));</code>

As of Laravel 5.1.25, use the useCurrent() column modifier:

<code class="php">$table->timestamp('created_at')->useCurrent();</code>

For ON UPDATE clauses, we can use DB::raw():

<code class="php">$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));</code>

Since Laravel 8.36.0, use the useCurrentOnUpdate() modifier:

<code class="php">$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();</code>

Gotchas:

  • MySQL: Since version 5.7, 0000-00-00 00:00:00 is no longer a valid date. Set a valid default or use nullable() timestamps.
  • PostgreSQL & Laravel 4.x: Specify a zero precision for CURRENT_TIMESTAMP to avoid microsecond parsing issues.
<code class="php">$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP(0)'));</code>

The above is the detailed content of How to Set Laravel Timestamps to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP?. 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