Allow login using username or email in Laravel 5.4

后端 未结 10 2221
南旧
南旧 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 01:18

    This is the way I do it:

    // get value of input from form (email or username in the same input)
     $email_or_username = $request->input('email_or_username');
    
     // check if $email_or_username is an email
     if(filter_var($email_or_username, FILTER_VALIDATE_EMAIL)) { // user sent his email 
    
        // check if user email exists in database
        $user_email = User::where('email', '=', $request->input('email_or_username'))->first();
    
        if ($user_email) { // email exists in database
           if (Auth::attempt(['email' => $email_or_username, 'password' => $request->input('password')])) {
              // success
           } else {
              // error password
           }
        } else {
           // error: user not found
        }
    
     } else { // user sent his username 
    
        // check if username exists in database
        $username = User::where('name', '=', $request->input('email_or_username'))->first();
    
        if ($username) { // username exists in database
           if (Auth::attempt(['name' => $email_or_username, 'password' => $request->input('password')])) {
              // success
           } else {
              // error password
           }
        } else {
           // error: user not found
        }
     }       
    

    I believe there is a shorter way to do that, but for me this works and is easy to understand.

提交回复
热议问题