我正在尝试根据角色类型在Eloquent模型上设置隐藏属性。例如,我在下面编写的宏将调整集合中的模型,以隐藏给定角色的字段。
Collection::macro('roleRestrict', function () {
switch (true) {
case RoleChecker::isUserGuest():
return $this->map(function (AuthorisedAttributeInterface $model) {
$model->setGuestRoleHiddenFields();
return $model;
});
default:
return $this;
}
});
可与MyModel::all()->roleRestrict()
一起使用
是否可以编写一个类似的宏,该宏适用于集合外部的单个模型对象?这将执行如下:
MyModel::findOrFail($id)->roleRestrict()
或者即使模型急于加载一个belongsTo关系:
AnotherModel::with('myModelRelationship')->findOrFail($id)->roleRestrict()
我最近为此写了一个小包...通过宏向Eloquent模型添加方法:
https://github.com/javoscript/laravel-macroable-models
检查出来,让我知道它是否有用! =)