Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check If user has a role In Laravel 5.5

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.

like image 266
Manjunarth Avatar asked Jan 30 '23 07:01

Manjunarth


1 Answers

if(Auth::user()->hasRole('admin'))

should work.

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

like image 79
Dessauges Antoine Avatar answered Feb 05 '23 15:02

Dessauges Antoine