Returning JSON with Dates and Accessors

Posted 3 years ago by bradroberts

Hey everyone,

In my Task model, I have a due_at field. When returning the model as JSON, due_at is a string:

due_at: "2016-07-18 00:00:00"

Nice!

However, if I create an accessor for due_at,

public function getDueAtAttribute($value) {
     // Some logic here to manipulate $value
     return new Carbon($value);
}

due_at is now returned as a JSON representation of the Carbon object:

{date: "2016-07-18 00:00:00.000000", timezone_type: 3, timezone: "UTC"}

I'd like for it to be a string, but only when returning the model as JSON. I don't want to return a string in my accessor, because I lose the ability to interact with the Carbon object in other scenarios (templates, etc).

Any ideas? I have added due_at to the $dates property on the model.

Thanks for your time!

Please sign in or create an account to participate in this conversation.