Laravel 7.x Login with Username Instead of Email Example

In this tutorial i will discuss about how to customize laravel default authentication and how we can log in vai username rather email. Laravel provide default login via email and password. But in this tutorial i wil show you how we can login using defalut auth via username and password in laravel. 

Sometime, we need to create login system with username and password to login. it's great function if you have in your website because it's really easy to remember username and easy to login. it's very easy to make auth login with username and password in laravel 7 application.

In this Laravel 7 login with username tutorial i will just customize the laravel default auth method. So let's start login with username in laravel tutorial.

 

Step 1 : Customize Login Blade

 

Read also : How to Set Limit Login Attempts in Laravel 7

First of all we need to customize laravel default login page. Here we will replace email by username. So follow the below code and update it like below.

resources/views/auth/login.blade.php

 

Step 2 : Modify AuthenticatesUsers Trait

Now if you visit login controller you will see, it uses AuthenticatesUsers trait. Look

App\Http\Controllers\Auth\LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

 

Now open this trait and modify username() method. By default it will return email but now we will return name. Go the the bottom of this below file you will get this method.

vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php

 public function username()
 {
   return 'name';
 }

 

Read also :  Laravel 7.x Custom Login and Registration Example

 

All are set to got. Now you can check it that laravel 7 login with username and password. Hope it can help you.