Allow login using username or email in Laravel 5.4

后端 未结 10 2231
南旧
南旧 2021-02-04 00:48

Now I\'ve followed the Laravel documentation on how to allow usernames during authentication, but it takes away the ability to use the email. I want to allow users to use their

10条回答
  •  庸人自扰
    2021-02-04 00:59

    You need to override protected function attemptLogin(Request $request) method from \Illuminate\Foundation\Auth\AuthenticatesUsers Trait in your LoginController i.e. in my LoginController class

    protected function attemptLogin(Request $request) {
    
        $identity = $request->get("usernameOrEmail");
        $password = $request->get("password");
    
        return \Auth::attempt([
            filter_var($identity, FILTER_VALIDATE_EMAIL) ? 'email' : 'username' => $identity,
            'password' => $password
        ]);
    }
    

    Your LoginController class should use Trait \Illuminate\Foundation\Auth\AuthenticatesUsers in order to override attemptLogin method i.e.

    class LoginController extends Controller {
    
         use \Illuminate\Foundation\Auth\AuthenticatesUsers;
         .......
         .......
    }
    

提交回复
热议问题