Laravel UI Auth: Login With Email Or Username Example

By Hardik Savani October 21, 2024 Category : Laravel

In this tips, I will show you how to login with email or username with laravel ui authentication.

Sometimes, we may need to let users log in using either their email or username. If you've implemented the Laravel UI Bootstrap authentication scaffold, how can you achieve this?

I'll walk you through a simple solution that allows users to log in with either their email or username.

First, navigate to the LoginController and override the username() method. By default, Laravel UI uses the username() method from the AuthenticatesUsers trait. We can easily customize it by overriding the method with the following code:

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 can also see the following video:

Output:

You can see the output:

I hope it can help you...

Tags :
Shares