Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

php - Dates not casting after upgrading to Laravel 7

I have just upgraded from Laravel 6 (PHP 7.4) to Laravel 7 (PHP 7.4) and casting dates in a model has completely stopped working.

For example, in my User model, I have the following $dates array:

protected $dates = [
    'online_at'
];

The following is returned: 2020-08-17T00:00:00.000000Z yet I am expecting a Carbon object to be returned.

The field in the MySQL database is DATETIME.

The same is happening with the created_at, updated_at, and deleted_at fields. It's also the same across all models.

I have tried moving the field into the $casts array but I get the same result.

Any help would be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models.

Previously, 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...