简体   繁体   中英

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.

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'.

Great answer, this worked well!

For those using Vue.js:

  1. Ensure that in Login.vue (resources/js/Pages/Auth/) you change the 'type' attribute of the 'email' input from 'email' to 'text' ( type="text" ), else you'll get a validation error. Also change the label value to "Username or Email".

  2. Ensure 'Register.vue' and 'UpdateProfileInformation.vue' (resources/js/Pages/Profile) has inputs for 'Username' in the template and username: this.user.username in the script data form.

  3. Ensure 'CreateNewUser.php' and 'UpdateUserProfileInformation.php' (app/Actions/Fortify/) methods include this field (with a 'unique' rule).

  4. Ensure the 'User' model has a field 'username' (unique, with associated db migration).

First as in the documentation Customizing User Authentication

    public function boot()
    {
        Fortify::authenticateUsing(function (Request $request) {
            $user = User::where('email', $request->email)->first();
    
            if ($user &&
                Hash::check($request->password, $user->password)) {
                return $user;
            }
        });
    
        // ...
    }

Filter your request:

$username = filter_var($request->email, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
Fortify::authenticateUsing(function (Request $request) {
            $username = filter_var($request->email, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
            $user = User::where($username, $request->email)
                ->first();
            if (
                $user &&
                Hash::check($request->password, $user->password)
            ) {
                return $user;
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM