TIMESTAMP COLUMN METHOD
Jan 19, 2024 Copy Link
When I was working on a Laravel project I faced an issue with the `timestamp`
method so, let me mimic the scenario that I faced with a nice example
There is a
`timestamp`
method in a singular form and this differs from the`timestamps`
method in a plural form.
Assume that we have a `products`
table that we already pre-created in that Article then, let's add a new `expire_date`
column using the `timestamp`
method. If we run the migration fresh command with the seed option, we will figure out that the column will be populated with the same values as the `created_at`
and `updated_at`
columns. Let's now open the Psy Shell
again to write the next code:
Do not forget to add that column to the
`$fillable`
property.
$product = \App\Models\Product::first();
$product->update(['expire_date' => now()->addDays(3)]);
The previous code will update the value of the `expire_date`
to be after three days in addition, the `updated_at`
column will be updated also and it's completely true, but what do you think the result is if we run the following code:
$product = \App\Models\Product::first();
product->update(['name' => 'Test Product Name']);
Actually, this code will update the `name`
and the `updated_at`
columns of the product till now everything is good but, you will discover that the `expire_date`
is updated too!
Oh..How did this happen?! 🤯
The reason behind that is if you open the table's structure you will discover that the `expire_date`
column has an ON UPDATE CURRENT_TIMESTAMP
extra attribute which makes its value change at any update that happens in the row
Hmm..So, what should I do to solve that issue? 🤔
I solved that issue by replacing the `timestamp`
with the `date`
method and everything works well now
You can replace that method with the best one that matches your scenario, in my case I did not need the full timestamps so I used the
`date`
method.
If we seed the database now after replacing the method an exception will be thrown that is because the
`timestamp`
column has a`CURRENT_TIMESTAMP`
default value whereas the`date`
does not so, we must assign a value to the`expire_date`
in the product factory.