How to Set Laravel Timestamps to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP?

DDD
Release: 2024-10-20 12:17:02
Original
247 people have browsed it

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>
Copy after login

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

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

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>
Copy after login

Since Laravel 8.36.0, use the useCurrentOnUpdate() modifier:

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

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>
Copy after login

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!