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.
- public function login(Request $request)
- {
- $field = filter_var($request->input('email_or_username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
- $request->merge([$field => $request->input('email_or_username')]);
- if (\Auth::attempt($request->only($field, 'password')))
- {
- return redirect('/');
- }
- return redirect('/login')->withErrors([
- 'error' => 'These credentials do not match our records.',
- ]);
- }
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.