问题
I am experiencing something quite weird for any Eloquent Model with Laravel 7!
P.S.: I've run on every test I did:
php artisan optimize:clear
I don't know what I am missing here!
I won't post any code because that's a simple CRUD with Model Bindings.
When saving the created_at and updated_at fields, it is correctly saved in the MySQL with my timezome "America/Sao_Paulo".
But if I do this in any controler:
return $model->get()
or
return $model->paginate()
or
Model::all()
I get the response:
{
"data": [
{
... other fields
"created_at": "2020-08-23T15:22:41.000000Z",
"updated_at": "2020-08-23T15:22:41.000000Z"
}
]
}
And it returns the wrong time with +1 hour.
However, here is where things get weird... if I print_r() any of them, I get the corret time!
Array
(
... other fields
[created_at] => 2020-08-23 12:22:41
[updated_at] => 2020-08-23 12:22:41
)
I tried to use:
public function getDateFormat()
{
return 'Y-m-d H:i:s';
}
But no effect!
Thanks in Advance!
回答1:
Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models with UTC
Before Laravel 7, dates would be serialized to a format like the following :
2019-12-02 20:01:00
Dates serialized using the ISO-8601 format will appear like :
2019-12-02T20:01:00.283041Z
Please note that ISO-8601 dates are always expressed in UTC.
If you would like to keep using the previous behavior you can override the serializeDate()
method on your model :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
See the official upgrade doc here
回答2:
If you have changed the timezone config in config/app.php but saving the date in the database with other timezone formats then keep the timezone to UTC so laravel doesn't change it to other formats when calling it from model class, or you can do the opposite by saving it by UTC format in database then change the config to a timezone that your app needs.
// config/app.php
'timezone' => 'UTC',
来源:https://stackoverflow.com/questions/63549021/wrong-timezone-with-eloquent-model-timestamps-on-model-get-but-correct-with