Laravel Attribute Casting DateTime

Viewed 5884

In database, in created_at field I have value "2020-10-04 20:46:14". In model "Entry" i have this code

protected $casts = [
    'created_at' => 'datetime:d.m.Y H:i',
];

In front app I get value "04.10.2020 18:46". In config/app.php I have timezone config 'timezone' => 'Europe/Berlin'.

Does someone knows what is the problem? Why casts change the time?

2 Answers

Whenever you use Carbon object in your response, its toJson() method is being called. The thing is, this method always displays time in UTC timezone. In other words, when it's 20:46 in Berlin, in UTC time (in London, for example), it's 18:46.

I agree that this behavior is confusing.

To fix it, either specify your custom format or use your model in response to take advantage of the format in your $casts. A quick fix would be:

// your controller method

return [
   'foo' => $entry->created_at->toDateTimeString(),
];

You can take a look at this question: Laravel Carbon returns incorrect time

Your date format for casting looks wrong. It should match the date time format stored in the database:

protected $casts = [
    'created_at' => 'datetime:Y-m-d H:i:s',
];

You should format the date differently, when displaying it {{ $model->created_at->format('d.m.Y H:i') }} but the cast should match the original format.

Related