如何使用 Laravel 在登录中添加 Spatie 角色条件

How to add Spatie Role Condition in Login using Laravel

我正在使用 Laravel-8,laravel-passport 和 spatie-permission for restful api。我已经在控制器中有了这段代码。

我有这个管理员控制器:

public function adminLogin(Request $request)
{
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success, 'User login successfully.');
    }
    else{
        return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
    }
}

我只希望 'Super Admin' 能够使用 Admin Controller 登录。如果不是'Super Admin',应该表示unathorized。

如何将下面的代码添加到我上面已有的代码或任何其他最佳方法中?

    if($user->hasRole('Super Admin'))
        $res = User::with(['roles', 'employee', 'company'])->find($user->id);
    else
        $res = User::with('roles')->find($user->id);

您可以在尝试验证后检查用户的角色。

public function adminLogin(Request $request)
{
    if (Auth::attempt($request->only('email', 'password'))) {
        $user = Auth::user();

        if (!$user->hasRole('Super Admin') {
            Auth::logout();

            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        }

        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success, 'User login successfully.');
    }

    return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}