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

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

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

1public function authenticate()
2{
3 $this->ensureIsNotRateLimited();
4 
5 if (! Auth::attempt($this->only('username', 'password'), $this->boolean('remember'))) {
6 RateLimiter::hit($this->throttleKey());
7 
8 throw ValidationException::withMessages([
9 'email' => trans('auth.failed'),
10 ]);
11 }
12 
13 RateLimiter::clear($this->throttleKey());
14}

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.

1public function boot()
2{
3 // ...
4 
5 Fortify::authenticateUsing(function (Request $request) {
6 $user = User::where('username', $request->username)->first();
7 
8 if ($user &&
9 Hash::check($request->password, $user->password)) {
10 return $user;
11 }
12 });
13}

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:

1public function username()
2{
3 return 'email';
4}

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

No comments or questions yet...

Like our articles?

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