通过在AuthenticatesAndRegistersUsers.php中更改,使用电子邮件和用户名登录

时间:2015-02-18 18:44:37

标签: laravel laravel-5

我正在使用laravel 5.我需要使用用户名或电子邮件登录我的用户。我正在从AuthenticatesAndRegistersUsers.php文件中更改以下代码:

public function postLogin(Request $request)
{


    $this->validate($request, [
        'email' => 'required', 'password' => 'required',
    ]);



    $credentials = $request->only('email', 'password');

    if ($this->auth->attempt($credentials, $request->has('remember')))
    {
        return redirect()->intended($this->redirectPath());
    }

    return redirect($this->loginPath())
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'email' => 'These credentials do not match our records.',
                ]);
}

使用以下代码。

public function postLogin(Request $request)
{


    $field = filter_var($request->input('loginfield'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';


    $this->validate($request, [
        'loginfield' => 'required', 'password' => 'required',
    ]);



    if ($this->auth->attempt([$field=> $request->only('loginfield'), 'password'=>$request->only('password')], $request->has('remember')))
    {
        return redirect()->intended($this->redirectPath());
    }

    return redirect($this->loginPath())
                ->withInput($request->only('loginfield', 'remember'))
                ->withErrors([
                    'email' => 'These credentials do not match our records.',
                ]);
}

我还相应地从login.blade.php更改了代码。但是当我将凭据传递给它时。它会抛出错误"电子邮件字段是必需的。"在login.blade.php中,我做了两处更改。 1.更改了输入类型" email" to" text" 2.来自"电子邮件"到" loginfield"。我做错了吗?

1 个答案:

答案 0 :(得分:1)

如果我们想要实现自己的要求,则在AuthController中覆盖postLogin方法是解决方案,而不是更改供应商目录。