Search code examples
laraveleloquent

When retrieving a datetime in Laravel, the application considers UTC, even if previously adjusted


Even configuring the timezone in Laravel I have problems recovering saved data.

I configured the timezone in config/app.php:

'timezone' => 'America/Sao_Paulo'

The records are being saved correctly, for example: 20:00:00.

However, when I retrieve the result in a query, it returns the time in UTC (23:00:00).


Solution

  • This is working as intended.

    https://laravel.com/docs/10.x/eloquent-mutators#date-casting-and-timezones

    By default, the date and datetime casts will serialize dates to a UTC ISO-8601 date string (YYYY-MM-DDTHH:MM:SS.uuuuuuZ), regardless of the timezone specified in your application's timezone configuration option. You are strongly encouraged to always use this serialization format, as well as to store your application's dates in the UTC timezone by not changing your application's timezone configuration option from its default UTC value. Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries written in PHP and JavaScript.

    If a custom format is applied to the date or datetime cast, such as datetime:Y-m-d H:i:s, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application's timezone configuration option.

    Simply specify your date columns in your model's $casts property to override this behavior

    class YourModel extends Model
    {
        protected $casts = [
            'your_date_field' => 'datetime:Y-m-d H:i:s',
        ];
    }
    

    Laravel 11 syntax:

    class YourModel extends Model
    {
        protected function casts(): array
        {
            return [
                'your_date_field' => 'datetime:Y-m-d H:i:s',
            ];
        }
    }