Home  >  Article  >  Backend Development  >  How Do I Set the Default Timestamp to the Current Timestamp in Laravel Migrations?

How Do I Set the Default Timestamp to the Current Timestamp in Laravel Migrations?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 11:40:02539browse

How Do I Set the Default Timestamp to the Current Timestamp in Laravel Migrations?

Laravel Migrations: Setting Default Timestamp to Current Timestamp

In Laravel, timestamps are commonly used to track activity, such as when a record was created or updated. By default, these timestamps are set to 0000-00-00 00:00. However, it can be useful to automatically set the default value to the current timestamp.

Using DB::raw()

For timestamps that you want to update regularly, you can use the DB::raw() function to specify CURRENT_TIMESTAMP as the default value:

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

This ensures that the created_at column will always contain the current timestamp, both when the record is initially created and when it is updated.

Using useCurrent() or useCurrentOnUpdate()

Alternatively, you can use the useCurrent() or useCurrentOnUpdate() methods to achieve the same result:

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

The useCurrent() method assigns the current timestamp as the default value for both creation and updates, while useCurrentOnUpdate() sets the default value for updates only.

MySQL ON UPDATE Clause

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

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

Gotchas

  • MySQL: Since MySQL 5.7, you may need to explicitly set a valid default value for timestamp columns, as 0000-00-00 00:00:00 is no longer accepted.
  • PostgreSQL & Laravel 4.x: In Laravel 4.x, you may experience issues with parsing timestamps if you use CURRENT_TIMESTAMP with a default precision. Use CURRENT_TIMESTAMP(0) instead to avoid this.

The above is the detailed content of How Do I Set the Default Timestamp to the Current Timestamp 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