如果不允许用户角色 Laravel,如何抛出错误

How to throw an error if user role is not allowed Laravel

我正在尝试利用 Laravel 身份验证系统并添加不允许您在拥有 user 用户角色时登录的逻辑。我想扩展验证用户。

protected function sendLoginResponse(Request $request)
{
    $user = $this->guard()->user();

    $request->session()->regenerate();
    if ($user->role != 'admin') {
        return redirect()->back()->with('error', 'You do not have permissions to view this page');

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }
}

问题是它仍然让我登录。我怎样才能使这个逻辑起作用?

将此函数添加到您的 LoginController,它将覆盖默认函数并添加额外的登录约束:

/**
 * override to add check
 * 
 * @param \Illuminate\Http\Request $request
 * @return array
 */
protected function credentials(Request $request)
{
    $credentials = $request->only($this->username(), 'password');
    $credentials['role'] = 'admin'; //only login admin

    return $credentials;
}