【问题标题】:Laravel auth attempt receiving a parameter from column tableLaravel auth 尝试从列表中接收参数
【发布时间】:2016-12-31 09:20:19
【问题描述】:

这是我的AccountController 课程:

public function postLogin(Request $request) {
    if (Auth::attempt(['email' => $request ['email'], 'password' => $request ['password']]) ) {
        $auth = \Auth::user()->role_id;

        switch($auth){
            case '1': return redirect()->route('admin/index');
            break;
            case '2': return redirect()->route('client/home');
            break;
            case '3': return redirect()->route('messenger/home');
            break;
        }
    }
}

如果只有特定用户的 confirmation_code 值是 true/1,我希望我的 Auth::attempt 方法登录用户。

我该怎么做?在 Auth::attempt 函数中接受特定用户的确认码?

【问题讨论】:

    标签: php laravel authentication


    【解决方案1】:

    只需将confirmation_code 添加到您要传递给attempt() 方法的数组中:

    Auth::attempt([
        'email' => $request['email'],
        'password' => $request['password'],
        'confirmation_code' => true,
    ]);
    

    Laravel 的 authentication manual 明确指出您可以添加任意条件。引用:

    如果您愿意,除了用户的电子邮件和密码之外,您还可以在身份验证查询中添加额外的条件。例如,我们可以验证用户是否被标记为“活跃”:

    if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
        // The user is active, not suspended, and exists.
    }
    

    如果你好奇,下面是under the hood;注意foreach:

    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials)) {
            return;
        }
    
        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.
        $query = $this->createModel()->newQuery();
    
        foreach ($credentials as $key => $value) {
            if (! Str::contains($key, 'password')) {
                $query->where($key, $value);
            }
        }
    
        return $query->first();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多