Force Eloquent Models to output all timestamps as long

佐手、 提交于 2019-12-24 06:41:15

问题


I'm working on a backend using Eloquent Models. In order to set a default way to output dates, I'm looking for a way to tell the Eloquent Model to output its date attributes as a long (unix-timestamp).

$user = User:find(id);
echo $user->toJson();

// the current output

{
   "id":1,
   "username":"root",
   "created_at":"2016-12-25 18:23:34",
   "updated_at":"2016-12-25 18:23:34"
}

// the desired output

{
   "id":1,
   "username":"root",
   "created_at":1482690214,
   "updated_at":1482690214
}

Is there a clean way to override the outputing toJson() or any other way to achieve this?

Edit

Do you thing that it's a good idea to override the magic __get()? Or does Eloquent use another way to access the attribute when calling toJson?


回答1:


Set desired format to $dateFormat variable:

protected $dateFormat = 'U';

By default, timestamps are formatted as Y-m-d H:i:s. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON

https://laravel.com/docs/5.3/eloquent-mutators#date-mutators



来源:https://stackoverflow.com/questions/41323970/force-eloquent-models-to-output-all-timestamps-as-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!