检查用户是否在 Laravel 5.5 中具有角色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47029894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check If user has a role In Laravel 5.5
提问by Manjunarth
I'm using entrust package to manage roles and I have used passport for authentication since it is API's.
我正在使用 entrust 包来管理角色,并且我已经使用通行证进行身份验证,因为它是 API 的。
Actually what I need is want to check user has a role,
其实我需要的是想检查用户有一个角色,
I have tried with below code but it doesn't work
我试过下面的代码,但它不起作用
public function Adminlogin()
{
if(Auth::attempt(['email' => request('email'), 'password' => request('password')]))
{
$user = Auth::user();
if($user->hasRole('admin'));
{
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
return response()->json(['error'=>'Abort'], 403);
}
else
{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
I want to generate access token only if user has admin role,If user has no role admin then show abort message.
我只想在用户具有管理员角色时生成访问令牌,如果用户没有管理员角色,则显示中止消息。
回答by Dessauges Antoine
if(Auth::user()->hasRole('admin'))
should work.
应该管用。
But you don't explain what is not working in your case so...
但是你没有解释什么在你的情况下不起作用所以......