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