In this example, we will see how to change email to username in laravel auth. For doing that, first of all we need a laravel default auth system. After making the auth system in laravel, we can implement login with username instead of email laravel 9.
To do laravel 9 change email to username, laravel provides a convenient way. From the laravel LoginController, we can do laravel change email to username before login. Just add the username() method and return the username
. That's it.
app/Http/Controller/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
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 = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'username';
}
}
Now pass the username from your HTML form like:
<input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
Read also: Laravel Passwordless Login | Login With Username In Laravel
Conclusion
Now we know how to change email to username in laravel auth. Hope this login with username instead of email laravel 9 tutorial will help you to custom login system with username in laravel application.