login with username or email in laravel 5

login with username or email in laravel 5

Sometime we will have to give chance to user to login with their username or email within the application.

In login form there will be one field and user will have option to enter either email or username with their password to login.

  1. public function login(Request $request)
  2. {
  3. $field = filter_var($request->input('email_or_username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
  4. $request->merge([$field => $request->input('email_or_username')]);
  5. if (\Auth::attempt($request->only($field, 'password')))
  6. {
  7. return redirect('/');
  8. }
  9. return redirect('/login')->withErrors([
  10. 'error' => 'These credentials do not match our records.',
  11. ]);
  12. }

In the above example, we use PHP filter FILTER_VALIDATE_EMAIL to validate input data is a valid email address or not.

If request have valid email address then we will authenticate with "email" field otherwise we will authenticate with "username" field.

Phone: (+91) 8800417876
Noida, 201301
sakarya escort sakarya escort sakarya escort