Force eloquent to use mutators during serialization

守給你的承諾、 提交于 2019-12-24 13:33:39

问题


Is there a way to force eloquent to use mutators when serializing data? I am currently converting my app to use vue.js and several fields are computed within the model, which I need to be included, in the serialized data.

Eloquent\Model - make toArray() utilize mutators

I understand why Taylor does not honour mutators but is there a way to override this behaviour?


回答1:


Before returning the model, you can do this

$model->setAppends(['mutator_1', 'mutator_2']);
return $model->toArray();

if you want to use it on a collection :

$collection->each(function($model) { $model->setAppends(...); });



回答2:


You can define which getters should be serialized like this:

protected $appends = ['is_admin'];

More info: Appending Values to JSON



来源:https://stackoverflow.com/questions/47692245/force-eloquent-to-use-mutators-during-serialization

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