Search code examples
phplaravellaravel-8laravel-authenticationlaravel-fortify

Login with either email or username with Fortify Laravel 8


I'm trying to allow users to login using either email or username along with their password.

I've added the following code inside boot() in FortifyServiceProvider.php :

Fortify::authenticateUsing(function (Request $request) {
        $user = User::where('email', $request->email)
            ->orWhere('username', $request->username)
            ->first();

        if ($user &&
            Hash::check($request->password, $user->password)) {
            return $user;
        }
    });

But now when users try to login by entering their username instead of email they get the following error message:

These credentials do not match our records.

Solution

  • I've forgotten to change the following line:

    ->orWhere('username', $request->username)
    

    To:

    ->orWhere('username', $request->email)
    

    Because simply there is only one field in my login form that can hold either email or username. The name of this field is 'email'.