authentication login with username or email in laravel
login with username or email in laravel 5 Example
Laravel comes with simple store auth out-of-the-box authorization email or password mechanism which is simple security incredibly easy to use. But it all the depends on several pre-defined function or things, one of the simple main purpose ones – DB table of any users structure and mechanism for login with email address field. What if we want to have email or username to identify a clients?authentication login with username or email in laravel Example
login with username or email in laravel 5
public function login(Request $request) { $field = filter_var($request->input('email_address_username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; $request->merge([$field => $request->input('email_address_username')]); if (\Auth::attempt($request->only($field, 'password'))) { return redirect('/'); } return redirect('/login')->withErrors([ 'error' => 'These specific credentials have not match our admin panel records.', ]); }
Routing using Laravel
php artisan make:auth
laravel 5.3 or more version login with username or email Example
All we some need is add a just property in app/Http/AuthController.php:
protected $username = 'username'; Illuminate\Foundation\Auth\AuthenticatesUsers.php public function postLogin(Request $request) { $this->validate($request, [ $this->loginUsername() => 'required', 'password' => 'required', ]);
And then let’s look into loginUsername() method.
public function loginUsername() { return property_exists($this, 'username') ? $this->username : 'email'; }
laravel Auth login with username or email
and in we AuthenticatesAndRegisterUsers.php we can change email address to simple username also.
public function postLogin(Request $request_data) { $this->validate($request_data, [ 'username' => 'required', 'password' => 'required', ]); $credentials = $request_data->only('username', 'password'); if ($this->auth->attempt($credentials, $request_data->has('remember'))) { return redirect()->intended($this->redirectPath()); } return redirect($this->loginPath()) ->withInput($request_data->only('username', 'remember')) ->withErrors([ 'username' => $this->getFailedLoginMessage(), ]); }