Skip to content
Advertisement

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement