How to handle JSON responses for models that include Carbon dates on Laravel? How to handle JSON responses for models that include Carbon dates on Laravel? json json

How to handle JSON responses for models that include Carbon dates on Laravel?


This might come in a bit late, but I usually make use of accessors and mutators to achieve this. For example, if I want all created_at and updated_at fields always to be returned in the ATOM format, I create a base model class extending Eloquent which every other model inherits:

use Carbon\Carbon as Carbon;use Illuminate\Database\Eloquent\Model as Model;class BaseModel extends Model {    public function getCreatedAtAttribute($value)    {        return Carbon::parse($value)->toATOMString();    }    public function setCreatedAtAttribute($value)    {        $this->attributes['created_at'] = Carbon::parse($value)->toDateTimeString();    }    public function getUpdatedAtAttribute($value)    {        return Carbon::parse($value)->toATOMString();    }    public function setUpdatedAtAttribute($value)    {        $this->attributes['created_at'] = Carbon::parse($value)->toDateTimeString();    }}


First, I suggest that you separate API from controllers. Use resources for API calls.

For the object returned to Laravel, I don't know how are you processing it to get the error, but you should initiate a new Carbon instance if you want a Carbon date. Else you could just return the date as a string, Laravel's Model will handle the rest.

Assuming the object returned is:

{    "delivered_at":{"date":"2014-02-25 12:55:29","timezone_type":3,"timezone":"America\/Argentina\/Buenos_Aires"}}

And the variable $data will have the current response, you could simply overwrite delivered_at:

$data->delivered_at = $data->delivered_at->date;

Or if you want a Carbon object:

$data->delivered_at = new \Carbon\Carbon($data->delivered_at->date, $data->delivered_at->timezone);


This may not be the same but I would get this error when working with timestamps and carbon but using strtotime() on the data i was passing resolved my issue, may help you.