Laravel 8 Login with User name in 2 steps| Laravel 8 Auth login with user

Laravel is good at providing lots of great features in itself and also they are fully customizable. One of them is Laravel's authentication system. In default Laravel Provides authentication using user's email address and password. But we can also use user's user name and password for the authentication (login) purpose with very little change. So in this article we will see how we implement authentication using user name instead of email address with minimal customization in our default Laravel Authentication system.

We will achieve the this feature just by modifying the Laravel's default authentication method with simple 2 steps, lets start.

Step 1 : Replace email input filed in login view with user name

Open Login blade view and just replace the email input field with user name as shown below.

resources/views/auth/login.blade.php

 <div class="col-md-6">
   <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>

     @error('name')
       <span class="invalid-feedback" role="alert">
          <strong>{{ $message }}</strong>
       </span>
     @enderror
  </div> 

If you have followed step 1 we will see in login page the email field is changed to user name field.

Step 2 : Return user name from AuthenticatesUsers Trait

Open App\Http\Controllers\Auth\LoginController.php and you will see AuthenticatesUsers trait.

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; //This is the trait

    protected $redirectTo = '/home';

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

Now open this trait and find username**() method. By default it will return **email . if we return name from this method then user can provide user name for login. Just scroll down to bottom and you will see the method and replace return "email" with return "name" and you are ready to go.

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

 /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'name';
    } 

This method will look the name column of your database. If you have changed the database or migration columns for name field then return accordingly.

Hope this article helped you and you have learned something from here. If you have any question feel free to leave comment. Thank you.

Comments :