Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow login using username or email in Laravel 5.4

Tags:

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'; } 
like image 848
Paul Lucero Avatar asked Mar 10 '17 02:03

Paul Lucero


2 Answers

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; } 
like image 121
Rabah Avatar answered Sep 22 '22 13:09

Rabah


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.

like image 26
EddyTheDove Avatar answered Sep 22 '22 13:09

EddyTheDove