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?
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>
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>
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>
Gotchas:
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!