Laravel 7 - created_at shows wrong datetime in datatable

Viewed 1731

in database I have stored date in field created_at for storage logs. Problem is that date in database is different from displayed in datatable.

Here is a screenshot from database row: enter image description here

And result in displayed datatable: enter image description here

Timezone in database looks correct for Poland +2H:

enter image description here

Also every new content added to database shows correct date. Timezone in Laravel is set to Europe/Warsaw which is correct. Date format is casted in logs model to prefered format:

class StorageLog extends Model
{
    protected $table = "storage_logs";
    public $timestamps = true;

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

Here is a code that calls database and returns data:

 $logs = StorageLog::select('id', 'id_storage_product', 'id_user', 'log', 'created_at')
 $result = $logs->orderBy('id', 'DESC')->paginate(20, ['*'], 'page', 1);

Result using DD function: enter image description here

Many thanks for any help with problem. Have a nice day!

2 Answers

Go to config/app.php and check your timezone:

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'Europe/Berlin',

By default the timezone is set to UTC and if you want to store the correct time with Laravel you need to set the correct timezone.

And one more thing... that time will be taken from the OS where the Laravel is running. So first set that correctly and then in Laravel.

This is the issue https://github.com/yajra/laravel-datatables/issues/2688

DataTable auto convert created_at and deleted_at fields to that format (unknown reason, I haven't found it anywhere in the package). There are many possible solutions to fix that. You can change the column name before parsing it to DataTable or you can use editColumn:

return DataTables::of($data)->editColumn('created_at', function ($user) {
    return $user->created_at;
});
Related