Try $date->toIso8601String();
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.
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.