Login Using Email Or Username In Laravel

A quick great tip for you guys. Laravel default authentication allows you to login with an email address and password field but what if you want to use some other field name like username/mobile number.

Laravel by default only allows one field email for login but we can also use username or Mobile number with it as well.

So today i’m going to tell you how can you able to login with username and mobile number field.

You need following things before do that stuff.

  • Laravel Project already setup in your system or site built with laravel.
  • Make sure you have users table in DB.
  • You have also make sure about “username” field name is already there in that users table.
  • Once you have this all now you ready to override the existing login functionality.

Now letโ€™s setup back-end logic for our new login. Go to LoginController.php file present in app/Http/Controllers/Auth directory. Hereโ€™s the updated code for the LoginController.php file.

In your LoginController.php file do the following changes carefully and you have done :).

First you have to define protected $username variable

protected $username;

Then go to the __construct() method and add variable there.

$this->username = $this->findUser();

and then add findUser() method inside the LoginController.php

     * Get the login username to be used by the controller.
     *  Either Username or Email
     * @return string
    public function findUser(){
        $login = request()->input('login'); // Your login form email/username input field name
        $fieldName = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        request()->merge([$fieldName => $login]);
         return $fieldName;

Now please save your controller file and remain untouched all other functions in same.

Now go to login page and you may now able to login using username or email

I hope this article helps you in your trouble, Thanks for reading. ๐Ÿ™‚ ๐Ÿ™‚ ๐Ÿ™‚

Leave a Reply