Use ‘Email or Anything Else’ For User Login In Laravel (v5.3)

in laravel by default the used field for login is email which you can find it under the ‘AuthenticatesUsers’ trait in ‘App\Http\Controllers\Controller\LoginController’

public function username()
  return 'email';

This is a very simple & useful method cuz now if you want to allow the user to login with something else other than the email then all you have to do is to simply override this method with the other field you want ex.‘username, phone, etc…’ and you are done.

But what if you want to have the best of the two worlds, give the user the chance to login by either the email or whatever else, so in this case lets see how we can make that.

1- under ‘resources/views/auth/login.blade.php’, lets edit the email input field to

{{-- Email / Username --}}
  {{ Form::label('identity', 'E-Mail Address / Username', ['class'=>'control-label']) }}
  {{ Form::text('identity', null, ['class'=>'form-control']) }}

2- now lets go to ‘App\Http\Controllers\Controller\LoginController’ and override the default methods with our new logic

protected $login_type;
protected $login_field = 'identity'; // so we can easily change the field name in the future

protected function validateLogin(Request $request)
  $this->login_type = filter_var($request->input($this->login_field), FILTER_VALIDATE_EMAIL)
    ? 'email'
    : 'username'; // or any other column name you want to use

    $this->login_type => $request->input($this->login_field),

  $this->validate($request, [
    $this->login_field => 'required',
    'password'         => 'required',

public function username()
  return $this->login_type;

protected function sendFailedLoginResponse(Request $request)
  // incase of ajax
  if ($request->wantsJson()) {
    return response()->json([
        $this->login_field => trans('auth.failed'),
    ], 422);

  // otherwise redir as usual
  return redirect()->back()
        $this->login_field => trans('auth.failed'),

3- and now you can login the user by either using the ‘email‘ or ‘username

Note that when you allow the user to login through anything other than the email, it have to be UNIQUE otherwise any user can login in-place of another if they have the same field value.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.