允许登录尝试,其中role = x或role = y

时间:2017-05-03 14:21:18

标签: php laravel-5 laravel-5.4

我知道可以通过向其传递数组来向try方法添加where查询。但是,允许具有特定角色的所有用户登录的登录表单呢?

尝试所有值会导致很多查询,所以是否有更优雅的想要检查是否允许用户登录?

/**
 * Attempt to log the user into the application.
 *
 * @param  \Illuminate\Http\Request $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    $values = ['admin', 'distributor']; //all roles that are allowed
    foreach ($values as $value) {
        if ($this->guard()->attempt(array_merge($this->credentials($request), ['role' => $value]), $request->has('remember'))) {
            return true;
        }
    }
    return false;
}

2 个答案:

答案 0 :(得分:0)

您必须手动登录用户。

protected function attemptLogin(Request $request)
{
    $values = ['admin', 'distributor']; //all roles that are
    $user = App\User::where(array_except($this->credentials($request), 'password'))->whereIn('role', $values)->first();
    if($user) {
        $this->guard()->login($user, $request->has('remember'));
        return true;
    }
    return false;
}

答案 1 :(得分:0)

在yazfields的帮助下,我找到了一个很好的解决方案:

/**
 * Attempt to log the user into the application.
 *
 * @param  \Illuminate\Http\Request $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    $query = User::query();
    $query->where($this->username(), $request->get($this->username()));
    $user = $query->whereIn('role', $this->allowedRoles)->first();
    if ($user) {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }
    return false;
}

首先,您尝试通过他的电子邮件地址(或用户名)获取用户并使用角色过滤他。如果您有匹配,请再次尝试登录用户。在这种情况下,您只需从Laravel扩展attemptLogin,并且最多有2个查询用于登录尝试。