In this article, I’ll walk you through customizing Laravel’s authentication system to allow users to log in with either their email or username. Laravel's default authentication system only supports email-based login, but with a few tweaks, you can enable multi-field login without any extra complexity.
This approach enhances user experience by providing flexibility during login.
We’ll use Laravel UI for this tutorial, modifying the default login
method to support both email and username logins.
Laravel UI Auth Login With Email Or Username
First, make sure you have Laravel UI installed in your Laravel 11 project. If you haven’t set up Laravel UI yet, follow these steps to install it and generate the basic authentication scaffolding:
composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
Run the migrations to create the users
table, which includes the name
and email
fields by default:
php artisan migrate
Now you should have the basic Laravel UI authentication setup
Open the LoginController.php located in app/Http/Controllers/Auth. Override the username() method to accept either an email or username as the log in field.
app/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('auth')->only('logout');
}
/**
* Write code on Method
*
* @return response()
*/
public function username()
{
$login_type = filter_var(request()->input("login"), FILTER_VALIDATE_EMAIL) ? "email" : "username";
request()->merge([
$login_type => request()->input("login")
]);
return $login_type;
}
}
You might also like: