Home > Backend Development > PHP Tutorial > How to Set a Timestamp Column\'s Default Value to the Current Timestamp and Update It On Modification in Laravel Migrations?

How to Set a Timestamp Column\'s Default Value to the Current Timestamp and Update It On Modification in Laravel Migrations?

Patricia Arquette
Release: 2024-10-20 12:17:30
Original
697 people have browsed it

How to Set a Timestamp Column's Default Value to the Current Timestamp and Update It On Modification in Laravel Migrations?

Setting Default Timestamp Column Value to Current Timestamp in Laravel Migrations

Question:

How can I define a timestamp column in Laravel migrations with a default value set to the current timestamp and update it to the current timestamp on modification?

Answer:

MySQL:

To set the default value of a timestamp column to the current timestamp and update it on modification in MySQL, you can use the useCurrent() and useCurrentOnUpdate() column modifiers:

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

PostgreSQL:

For PostgreSQL, no specific modifier is required. Simply using the timestamp() method will set the default value to the current timestamp:

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

Older Laravel Versions:

In Laravel versions prior to 5.1.25, you can use the DB::raw() method to set the default value:

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

Gotchas:

  • MySQL 5.7 : Ensure that MySQL is using a valid date range for timestamps.
  • PostgreSQL & Laravel 4.x: Explicitly set the precision of the timestamp value to 0 to avoid parsing issues.

The above is the detailed content of How to Set a Timestamp Column\'s Default Value to the Current Timestamp and Update It On Modification in Laravel Migrations?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template