Check If user has a role In Laravel 5.5

Manjunarth picture Manjunarth · Oct 31, 2017 · Viewed 8.8k times · Source

I'm using entrust package to manage roles and I have used passport for authentication since it is API's.

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.

Answer

Dessauges Antoine picture Dessauges Antoine · Oct 31, 2017
if(Auth::user()->hasRole('admin'))

should work.

But you don't explain what is not working in your case so...