Created
July 29, 2016 08:23
-
-
Save jewei/acb0e63a80632fb4db533a09013c9303 to your computer and use it in GitHub Desktop.
Laravel 5.x. Login authentication with username or email.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
use App\Http\Controllers\Auth\AuthController; | |
use Illuminate\Auth\CreatesUserProviders; | |
class LoginController extends AuthController | |
{ | |
use CreatesUserProviders; | |
protected $app; | |
protected $provider; | |
/** | |
* Handle a login request to the application with username or email. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function prelogin(Request $request) | |
{ | |
$this->app = app(); | |
$this->provider = $this->createEloquentProvider(config('auth.providers.users')); | |
// Authenticate with username or email. | |
$this->username = filter_var($request->username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; | |
$request->merge([$this->username => $request->input('username')]); | |
$credentials = $request->only($this->username, 'password'); | |
if ($user = $this->provider->retrieveByCredentials($credentials)) { | |
// You may also want to access the user modal. | |
// if ($user->hasRole('')) {} | |
return $this->login($request); | |
} | |
return $this->sendFailedLoginResponse($request); | |
} | |
/** | |
* Overwrite parent method so the correct login username input field has the | |
* error message. Otherwise, failed login message may not appear. | |
*/ | |
protected function sendFailedLoginResponse(Request $request) | |
{ | |
$this->username = 'username'; | |
return parent::sendFailedLoginResponse($request); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Route::auth(); | |
// Place this below Route::auth() to override post login. | |
Route::post('login', 'LoginController@prelogin'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment