Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

corykeane's avatar

Formatting dates in JSON/API response (ISO-8601 format)

Hello. I have done a bunch of research, and have not found any solid answer to this question.

I built an API with Laravel, and am trying to return any date fields in ISO-8601 format (https://en.wikipedia.org/wiki/ISO_8601).

I have tried overriding the serializeDate() function on all my models, but this leads to a "Unexpected data found. Trailing data" error with Carbon.

Here is the code I tried using in my models:

protected function serializeDate(\DateTimeInterface $date)
{
    return $date->format('c');
}

I believe things are failing here: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L673

Any ideas here? ISO-8601 is a standard, and many consider returning dates in this format as best practice.

0 likes
4 replies
corykeane's avatar

I understand that Carbon has that formatter built into the library.. However, this is more of a Laravel / Illuminate specific question.

In my API controllers, I am returning Eloquent Models, which are serialized into JSON. I want to continue to be able to return the eloquent models, meaning I need to figure out how to serialize model dates automatically.

corykeane's avatar
corykeane
OP
Best Answer
Level 1

To fix this issue, I had to remove created_at and updated_at from my protected $dates array property. It looks like if you add a standard date field to this array, things get a little weird. So now I am only adding my custom date fields (e.g. last_contacted_at field) to this array.

The getDates() function returns these fields twice if you include them in the $dates array. Cronix and I believe Laravel should be doing an array_unique() somewhere to catch these cases.

Please or to participate in this conversation.