Laravel Auth: Login With Email Or Username (In One Field)

Quick tip for you guys. What if in your project users can login not only with email but also with some other field, like "username" or "user_id" or whatever? By default Laravel allows only one field like 'email'. That's actually easy to change. Let's imagine that you already have a field username in your users table and need to check the login form result. So there are only two input fields - login and password. And login may be either email or username. How can we check both? You need to add some code into a file app/Http/Auth/LoginController.php and override login() method:
public function login(Request $request)
{
    $this->validate($request, [
        'login'    => 'required',
        'password' => 'required',
    ]);

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

    $request->merge([
        $login_type => $request->input('login')
    ]);

    if (Auth::attempt($request->only($login_type, 'password'))) {
        return redirect()->intended($this->redirectPath());
    }

    return redirect()->back()
        ->withInput()
        ->withErrors([
            'login' => 'These credentials do not match our records.',
        ]);
    }

}
Let's look a little deeper:
$login_type = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL )
  ? 'email'
  : 'username';
This line of code is checking whether user inputted an email or some other string - which then is interpreted as username.
$request->merge([
    $login_type => $request->input(β€˜login')
]);
This one is adding a variable into $request array - by default we have 'login' variable, but what we actually need is 'email' or 'username' - so it's inserted here.
if (Auth::attempt($request->only($login_type, 'password'))) {
    return redirect()->intended($this->redirectPath());
}
And finally we're checking the credentials, but only the particular one we need - it comes from $login_type variable. Simple, isn't it?
avatar

Is there a new one for laravel 9 ?

avatar

Not at the moment. But adding it to my to-do list, to update this article in upcoming weeks.

πŸ‘ 1

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

Recent Premium Tutorials