Auth: login with username instead of email

Tutorial last revisioned on August 22, 2022 with Laravel 9

Laravel offers a few starter kits to help you start quickly with authentication. But it depends on several pre-defined things, one of the main ones – DB table users structure and login with an email field. What if you want to have a username to identify a user? With every kit it's different how you would do it, so I will show to how to do it using Laravel Breeze, Laravel Jetstream and Laravel UI.

First, of course, you need to create a database migration to add a username column to your DB table, and don't forget to update your views.


Laravel Breeze

Breeze tries to authenticate the user in the App/Http/Requests/Auth/LoginRequest.php class, in authenticate() method. Just change this line

if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {

from email to username. So the whole method should look like this:

public function authenticate()
{
$this->ensureIsNotRateLimited();
 
if (! Auth::attempt($this->only('username', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
 
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
 
RateLimiter::clear($this->throttleKey());
}

Also, I have a video about logging in with email, name or phone. You can check it out here.


Laravel Jetsream

Jetstream uses Laravel Fortify for handling authentication. To save additional data, we will need to customize users authentication. Typically this should be done in the JetstreamServiceProvider, in the boot() method.

public function boot()
{
// ...
 
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('username', $request->username)->first();
 
if ($user &&
Hash::check($request->password, $user->password)) {
return $user;
}
});
}

Laravel UI

You need to know that there is AuthenticatesUsers trait. It\’s called every time someone logs in. You can check what methods this trait has in github repository. For our needs there is a username method that looks like this:

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

So it's simple as to override this method by just changing default the email to username in our case.

You can read more about Auth customization in this article: 8 Things You Can Customize in Laravel Registration

avatar

in the Laravel Breeze stack, in the authenticate() method, shouldn't the error bag also contain username instead of 'email' when returning errors?

avatar

Yes, if you also change the inputs in the blade. Error is shown for email by default https://github.com/laravel/breeze/blob/1.x/stubs/default/resources/views/auth/login.blade.php#L12

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 66 courses (1167 lessons, total 43 h 18 min)
  • 88 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses