


How to Set Laravel Timestamps to CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP?
Oct 20, 2024 pm 12:17 PMDefault 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
