问题
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