'Laravel 9 serializeDate() Not Working on Other Columns

I want to return json wit all the data with a timestamp datatype turned into ISO 8601 automatically. This should be easily achievable after Laravel 7 but I still face the issue.

I have created two columns start_time and end_time with the timestamp data type. While returning the results in JSON, Laravel only converts created_at and updated_at into ISO8601 (e.g. 2022-04-26T09:44:47.000000Z). The two columns I created are returned as they are stored in the database (e.g. 2022-01-17 19:45:07).

Anything I added in serializeDate() to replace the default method would only affect created_at and updated_at.

The closest I can get is to add below to my model, but it still has a slight difference in format (e.g. 2022-04-26T10:30:00Z vs 2022-04-26T09:44:47.000000Z).

protected $casts = [
        'start_time' => 'date:Y-m-d\TH:i:s\Z',
        'end_time' => 'date:Y-m-d\TH:i:s\Z',

    ];


Solution 1:[1]

This may not answer the questions directly but I found a workaround. What you can do is Carbon::parse those columns returned as stored in the database before returning them in Json.

Here is an example if you are returning all the slots in your database:

foreach ($slots as $slot) {
     $slot->start = Carbon::parse($slot->start_time);
     $slot->end = Carbon::parse($slot->end_time);
}

return response()->json($slots);

Solution 2:[2]

It's simply because you need to tell Laravel about the columns it should consider as dates in your model, by default created_at and updated_at are considered.

There is a protected property called $dates, it takes an array of all the columns to be considered as dates. the serializeDate method looks after that property.

protected $dates = [
    'reception_date',
    'response_date' ,
    '...'
];


protected function serializeDate(DateTimeInterface $date)
{
    // you may give whatever format you want
    return $date->translatedFormat('d M Y à H:i');
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andre W.
Solution 2 Vidral Bonvi