Laravel Login with Username Instead of Email

  • January 05, 2017

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Before implementing the steps that follow you'll first want to update your Laravel application's registration form and accompanying logic to accept a username. This is covered in the blog post Adding Custom Fields to a Laravel 5 Registration Form.

Laravel's default authentication scheme is configured to require users to supply an e-mail address and password. It's however often the case that you'll want to instead ask for a username and password. Presuming you've added the username field to your database and required the user to supply a username during registration, as described in the previous section, changing this requirement is incredibly easy. Begin by opening your resources/views/auth/login.blade.php view and modifying the e-mail block to instead ask for a username:

<div class="form-group{{ $errors->has('username') ? ' has-error' : '' }}">
    <label for="username" class="col-md-4 control-label">Username</label>

    <div class="col-md-6">
        <input id="username" type="username" class="form-control" 
          name="username" value="{{ old('username') }}" required autofocus>

        @if ($errors->has('username'))
            <span class="help-block">
                <strong>{{ $errors->first('username') }}</strong>
            </span>
        @endif
    </div>
</div>

Save the changes and open your app/Http/Controllers/Auth/LoginController.php file and add the following method to the LoginController class:

public function username()
{
    return 'username';
}

Save your changes and return to the login form. Provided you've populated the user record with a username, you'll be able to login using your account username and password!

Chapter 9 is devoted to integration user registration, login, and account profile management.

Buy the book