I just hit a snag with Eloquent's (Laravel 5.2.10) default timestamps. By default the $table->timestamps()
method gives you a created_at
and an updated_at
column in your table which are updated accordingly.
However, when I was trying some test entries, I noticed that when you update a record, the updated_at
field gets updated, as it should, but the created_at
field also gets updated: its hours stays at the created time, but the minutes and seconds get updated to match the updated_at
field.
If that was too wordy, here is an example:
+---------------------+---------------------+
| created_at | updated_at |
+---------------------+---------------------+
| 2016-01-13 17:13:27 | 2016-01-13 22:13:27 |
| 2016-01-13 16:14:41 | 2016-01-13 21:14:41 |
+---------------------+---------------------+
Notice that the minutes and seconds are the exact same for the created_at
and updated_at
field.
I tried to look through the Model
class where the timestamps are set, but it turns out the setCreatedAt()
method is indeed not called when just updating a record.
Why does this happen?
How do I prevent the created_at
field from changing? (more important)
Your issue is probably related to this issue here: https://github.com/laravel/framework/issues/11518
Long story short, many people's created_at
column had the ON UPDATE CURRENT_TIMESTAMP
attribute.
As stated on the Github page:
MySQL 5.7 no longer allows 0000-00-00 as a valid timestamp with strict mode turned on (which it is by default). So either use
->nullableTimestamps()
or->timestamp()->useCurrent()
.
So, you can fix this by changing this:
$table->timestamps();
To either one of these options:
// Option 1:
$table->nullableTimestamps();
// Option 2:
$table->timestamp('updated_at')->useCurrent();
$table->timestamp('created_at')->useCurrent();
Also, on this MySQL page: https://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
Alternatively, if
explicit_defaults_for_timestamp
is disabled (the default), do either of the following:Define the column with a DEFAULT clause that specifies a constant default value.
Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With