Home >Backend Development >PHP Tutorial >How Do I Set the Default Value of Timestamp Columns to CURRENT_TIMESTAMP and Auto Update in Laravel Migrations?

How Do I Set the Default Value of Timestamp Columns to CURRENT_TIMESTAMP and Auto Update in Laravel Migrations?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 12:26:02508browse

How Do I Set the Default Value of Timestamp Columns to CURRENT_TIMESTAMP and Auto Update in Laravel Migrations?

Setting Default Value of Timestamp Column to Current Timestamp in Laravel Migrations

Question: How can I create a timestamp column with a default value of CURRENT_TIMESTAMP and update it to CURRENT_TIMESTAMP in Laravel migrations?

Laravel's Schema Builder does not explicitly provide a method to set the default value of a timestamp column to CURRENT_TIMESTAMP.

Answer:

To set the default value to CURRENT_TIMESTAMP, use the DB::raw() method to define a raw expression:

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

For MySQL, you can additionally use the ON UPDATE clause within DB::raw():

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

As of Laravel 5.1.25, you can use the useCurrent() method to simplify this:

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

In Laravel 8.36.0 and above, useCurrent() can be used with the useCurrentOnUpdate() method for both default and on-update values:

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

Gotchas:

  • MySQL: Starting with version 5.7, 0000-00-00 00:00:00 is no longer valid as a timestamp. Use useCurrent() or allow null values.
  • PostgreSQL in Laravel 4.x: Specify a zero precision to the CURRENT_TIMESTAMP function to avoid microsecond errors.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP(0)'));

The above is the detailed content of How Do I Set the Default Value of Timestamp Columns to CURRENT_TIMESTAMP and Auto Update 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