Allow login using username or email in Laravel 5.4

2019-03-15 11:31发布

问题:

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 username or email to login. How do I go about this?

I've added this code to the LoginController as per Laravel's Documentation and it only allows username for login. I want it to accept username or email for login.

public function username () {
    return 'username';
}

回答1:

Follow instructions from this link: https://laravel.com/docs/5.4/authentication#authenticating-users

Then you can check for the user input like this

$username = $request->username; //the input field has name='username' in form

if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
    //user sent their email 
    Auth::attempt(['email' => $username, 'password' => $password]);
} else {
    //they sent their username instead 
    Auth::attempt(['username' => $username, 'password' => $password]);
}

//was any of those correct ?
if ( Auth::check() ) {
    //send them where they are going 
    return redirect()->intended('dashboard');
}

//Nope, something wrong during authentication 
return redirect()->back()->withErrors([
    'credentials' => 'Please, check your credentials'
]);

This is just a sample. THere are countless various approaches you can take to accomplish the same.



回答2:

I think a simpler way is to just override the username method in LoginController:

public function username()
{
   $login = request()->input('login');
   $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
   request()->merge([$field => $login]);
   return $field;
}


回答3:

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;
     .......
     .......
}


回答4:

Open your LoginController.php file.

  1. Add this reference

    use Illuminate\Http\Request;
    
  2. And override the credentials method

    protected function credentials(Request $request)
    {
        $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
        ? $this->username()
        : 'username';
    
        return [
            $field => $request->get($this->username()),
            'password' => $request->password,
        ];
    }
    

Successfully tested in Laravel 5.7.11



回答5:

I think its even more simple, just edit AuthenticatesUsers traits, credentials method. Here I have implemented to login with either email or phone. You can change it to fit your needs.

protected function credentials(Request $request)
{
    if(is_numeric($request->get('email'))){
        return ['phone'=>$request->get('email'),'password'=>$request->get('password')];
    }
    return $request->only($this->username(), 'password');
}


回答6:

This solution of "Rabah G" works for me in Laravel 5.2. I modified a litle but is the same

$loginType = request()->input('useroremail');
$this->username = filter_var($loginType, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$this->username => $loginType]);
return property_exists($this, 'username') ? $this->username : 'email';


回答7:

Thanks, this is the solution I got thanks to yours.

protected function credentials(Request $request) { 

$login = request()->input('email'); 

// Check whether username or email is being used
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'user_name'; 
return [ 
   $field    => $request->get('email'), 
  'password' => $request->password, 
  'verified' => 1 
]; 
} 


回答8:

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.