Laravel 5 returns date and time with time zone

I am creating an API and I would like to return all my timestamps such as created_at, deleted_at, ... etc. as complex objects, including the actual time and time, as well as the time zone. I already use {Carbon / Carbon} in my controller. I also defined my date field in the model. When I access date fields in my controller, I actually get Carbon objects. But when I return my result set as JSON, I only see the datetime string. Not a time zone.

Current json

{ "id": 4, "username": "purusScarlett93", "firstname": null, "lastname": null, "language_id": 1, "pic": null, "email": null, "authtoken": "f54e17b2ffc7203afe345d947f0bf8ceab954ac4f08cc19990fc41d53fe4eef8", "authdate": "2015-05-27 12:31:13", "activation_code": null, "active": 0, "devices": [], "sports": [] } 

My desire:)

 { "id": 4, "username": "purusScarlett93", "firstname": null, "language_id": 1, "pic": null, "email": null, "authtoken":"f54e17b2ffc7203afe41d53fe4eef8", "authdate": [ { "datetime": "2015-05-27 12:31:13", "timezone": "UTC+2" } ], "activation_code": null, "active": 0 } 

Any idea what I'm missing here?

+7
php eloquent laravel-5 php-carbon
source share
2 answers

This is because all Carbon objects have a __toString() function, which runs when you try to convert an object to a string (for example, JSON). Try to see if you can create your own accessory on your model, which gives you a custom array instead of a string.

 public function getAuthdateAttribute(Carbon $authdate) { return [ 'datetime' => $authdate->toDateTimeString(), 'timezone' => 'UTC' . $authdate->offsetHours ]; } 

As an Alariva user points out, this method will override your default authdate access method; therefore, if you want to access the original Carbon object, you may need to create a special method for it.

Or you can be a little smarter and do something like this:

 public function getAuthdateAttribute(Carbon $authdate) { return [ 'datetime' => $authdate, 'timezone' => 'UTC' . $authdate->offsetHours ]; } 

Then to access the source object: $carbon = $this->authdate['datetime']

0
source share

You can try to add such a function inside your model:

 public function getAuthDateAttribute() { return [ "datetime" => "2015-05-27 12:31:13", "timezone" => "UTC+2" ];} 
0
source share

All Articles