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