[英]Checking permissions in accessors in Laravel
I want to check does user have proper permission to get specific attribute from the User
model. 我想检查用户是否具有从User
模型获取特定属性的适当权限。
I already did example simple accessor, but it is not sufficient, because it doesn't remove/unset email
attribute from the User
collection. 我已经做过简单访问器示例,但这还不够,因为它不会从User
集合中删除/取消设置email
属性。
public function getEmailAttribute($value)
{
if(Auth::User()->hasPermissionTo('users.show.email')) {
return $value;
}
return false;
}
then I use User::Get()
and I get this output: 然后我使用User::Get()
并得到以下输出:
"name": "admin",
"email": "false",
...
Accessor works almost properly, but I want to hide email
attribute at all. 访问器几乎可以正常工作,但是我想完全隐藏email
属性。
You can achieve this by overriding the toJson
or toArray
method of the model itself, depending on which one you use. 您可以通过覆盖模型本身的toJson
或toArray
方法来实现此toJson
,具体取决于您使用的是哪种方法。 So for example the toJson
can look like this: 因此,例如toJson
可以如下所示:
public function toJson( $options = 0 )
{
if( ! auth()->user()->hasPermissionTo('users.show.email')) {
$this->hidden[] = 'email';
}
return parent::toJson($options);
}
Notice I use the inverse logic, because in any case you would want to return a result. 注意,我使用逆逻辑,因为在任何情况下您都想返回结果。 Same will be for the toArray
. 对于toArray
。 You should have this in your User
model. 您应该在您的User
模型中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.