Laravel 5返回带有时区的日期时间

Chr*_*ger 7 php eloquent php-carbon laravel-5

我正在构建一个API,我希望将所有时间戳(如created_at,deleted_at,...等)作为复杂对象(包括实际日期时间,还包括时区)返回.我已在控制器中使用{Carbon/Carbon}.我也在模型中定义了我的日期字段.当我访问控制器中的日期字段时,我实际上获得了Carbon对象.但是当我将结果集作为JSON返回时,我只看到日期时间字符串.不是时区.

目前的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": []
}
Run Code Online (Sandbox Code Playgroud)

我的希望 :)

{
  "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
 }
Run Code Online (Sandbox Code Playgroud)

知道我在这里缺少什么吗?

sil*_*ire 1

这是因为所有Carbon对象都有一个__toString()函数,当您尝试将对象转换为字符串(即 JSON)时,该函数就会被触发。尝试看看是否可以在模型上创建自己的访问器,为您提供自定义数组而不是字符串。

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

正如用户 Alariva 指出的,此方法将覆盖您的默认访问方式authdate;因此,如果您想访问原始Carbon对象,也许您必须为此创建一个特殊的方法。

或者你可以聪明一点,做这样的事情:

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

然后访问原始对象:$carbon = $this->authdate['datetime']