Login with email or phone number in Laravel

How to Login with email or phone number in Laravel


In this post, you will be learning how to login with email id or phone/mobile number or username in laravel.

Let's get started.

Step 1: Install your laravel application and get your database connected and migrate the tables.

Step 2: Create a migration file as follows

php artisan make:migration add_phone_to_users_table

After successful of creating migration, paste the below code in your last migration file. (2022_10_30_102257_add_phone_to_users_table.php)

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('phone')->unique()->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('phone');
        });
    }


Step 3: Go to the login.blade.php file in following path: resources/views/auth/login.blade.php 

In this file, change the <input type="email" /> to <input type="text" /> for the email input field as follows:

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


Step 4: Go to LoginController.php in the following path: app/http/controllers/auth/LoginController.php 

Paste the below code in your LoginController.php file

protected function credentials(Request $request)
{
    if(is_numeric($request->get('email'))){

        return ['phone'=>$request->get('email'),'password'=>$request->get('password')];
    }
    elseif (filter_var($request->get('email'), FILTER_VALIDATE_EMAIL)) {

        return ['email' => $request->get('email'), 'password'=>$request->get('password')];
    }

    return ['username' => $request->get('email'), 'password'=>$request->get('password')];
}


That's it, now you can login with your email id or phone number in laravel.

Thanks for reading.