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 the new starter kits, which were introduced with Laravel 12.
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 & New Starter Kits
Breeze and the new starter kits React and Vue versions tries to authenticate the user in the App/Http/Requests/Auth/LoginRequest.php
class, in the 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());}
Livewire kit have two options:
- Livewire components
- Class-based Volt components
For the Livewire component authentication component is app/Livewire/Auth/Login.php
. For the Volt component Blade file location is resources/views/livewire/auth/login.blade.php
. For your option, change the same code from email
to username
:
if (! Auth::attempt(['username' => $this->username, 'password' => $this->password], $this->remember)) {
With Livewire, don't forget to change the email public property and its validation.
From:
#[Validate('required|string|email')]public string $email = '';
To:
#[Validate('required|string')]public string $username = '';
Also, I have a video about logging in with email, name or phone using Breeze. 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; } });}
in the Laravel Breeze stack, in the authenticate() method, shouldn't the error bag also contain username instead of 'email' when returning errors?
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