Laravel 9 Firebase Phone Number OTP Authentication Tutorial

Phone number authentication is an uncomplicated method to authenticate and login into the app. It has numerous benefits like it is fast, secure, and gives you a sense of gratification by securing your time.

If you want to implement mobile number OTP (one-time-password) authentication in your laravel app, this tutorial is exclusively for you.

Throughout this comprehensive guide, you will comprehend how to add phone number OTP authentication in the Laravel app using the Firebase phone auth provider.

Firebase is a superior BaaS platform, comes with outstanding and significant features. It gives precedence to user experience and believes in bringing unbound happiness in users’ life.

You get tons of features with it, not just mobile number authentication, but it also provides tons of other social media auth providers to build auth system within less time.

Here is the plan for integrating Phone number OTP auth in the Laravel Firebase app.

You will be creating a laravel app using the composer command; discover how to build a Firebase project to get Firebase SDK.

Plus, make the controller tie it with routes to set up the view and create a phone number OTP auth form with Google ReCaptcha to authenticate.

Laravel 9 Firebase Phone Number OTP Authentication Example

  • Step 1: Download Laravel Project
  • Step 2: Connect to Database via ENV
  • Step 3: Get Firebase SDK
  • Step 4: Activate Phone Auth Provider
  • Step 5: Setting Up Controller
  • Step 6: Register New Route
  • Step 7: Create + Configure Blade View
  • Step 8: View App in Browser

Download Laravel Project

Downloading a new Laravel project is an utterly facile process; after setting up the Composer tool, open the terminal, type the provided command and let the project be installed on your system.

composer create-project --prefer-dist laravel/laravel laravel-firebase-demo

Step inside the newly created laravel app.

cd laravel-firebase-demo

Connect to Database via ENV

Database can be connected to laravel app, open .env file, and carefully update database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_username
DB_PASSWORD=db_password

Get Firebase SDK

Refer to firebase.google.com site, create a new firebase project.

Firebase Create Account

Let’s start with providing a name to your firebase project.

Create a project

Now, register the app and add firebase to your web app; you may also set up Firebase Hosting by checking on the tick box.

add Firebase to app

Next, provide a project name to include Firebase to your web app:

add firebase

After that, you need to copy the Firebase SDK; we will need it to connect laravel to Firebase.

Firebase configuration keys

Activate Phone Auth Provider

In order to create phone auth in laravel, you now need to click on the Authentication tab, then get into the sign-in providers’ page, click on the Phone auth option, and enable this service.

Firebase Phone Auth Provider

Setting Up Controller

Further, type the PHP artisan command in the terminal console to generate the new controller file.

php artisan make:controller FirebaseAuthController

The FirebaseAuthController is a single class that can add the programming logic; however, we are using it to invoke the view file.

Hence, update app/http/controllers/FirebaseAuthController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;


class FirebaseAuthController extends Controller
{

    public function index()
    {
        return view('index');
    }

}

Register New Route

Route can directly communicate with controller, earlier we build route to load the view file, so update the routes/web.php file to formulate the new route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FirebaseAuthController;



Route::get('/firebase-auth', [FirebaseAuthController::class, 'index']);

Create + Configure Blade View

To set up view create contact.blade.php file within the views folder, after that update offered code in resources/views/contact.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Laravel 8 Firebase Phone Number Auth with Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        .container {
            max-width: 500px;
            margin-top: 50px;
        }

    </style>
</head>

<body>
    <div class="container">
        <div class="alert alert-danger" id="showError" style="display: none;"></div>

        <h4>Phone number</h4>
        <div class="alert alert-success" id="authSuccess" style="display: none;"></div>

        <form>
            <div class="form-group mb-3">
                <input type="text" id="phoneNumber" class="form-control" placeholder="+91 #########">
            </div>

            <div class="form-group">
                <div id="recaptcha-container"></div>
            </div>

            <div class="d-grid mt-3">
                <button type="button" class="btn btn-dark" onclick="sendFirebasePhoneOTP();">Send OTP</button>
            </div>
        </form>


        <div class="mb-5 mt-5">
            <h3>Enter OTP</h3>
            <div class="alert alert-success" id="otpSuccess" style="display: none;"></div>
            <form>

                <input type="text" id="verfifyNumber" class="form-control" placeholder="Verification code">

                <div class="d-grid mt-3">
                    <button type="button" class="btn btn-danger mt-3" onclick="verifyPhoneNumber()">Authenticate</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase.js"></script>

    <script>
        var firebaseConfig = {
            apiKey: "API_KEY",
            authDomain: "PROJECT_ID.firebaseapp.com",
            databaseURL: "https://PROJECT_ID.firebaseio.com",
            projectId: "PROJECT_ID",
            storageBucket: "PROJECT_ID.appspot.com",
            messagingSenderId: "SENDER_ID",
            appId: "APP_ID",
            measurementId: "G-MEASUREMENT_ID",
        };
        firebase.initializeApp(firebaseConfig);
    </script>

    <script type="text/javascript">
        window.onload = function () {
            render();
        };

        function render() {
            window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
            recaptchaVerifier.render();
        }

        function sendFirebasePhoneOTP() {
            var phoneNumber = $("#phoneNumber").val();
            firebase.auth().signInWithPhoneNumber(phoneNumber, window.recaptchaVerifier)
            .then(function (confirmationResult) {
                window.confirmationResult = confirmationResult;
                coderesult = confirmationResult;
                $("#authSuccess").text("Message sent");
                $("#authSuccess").show();
            }).catch(function (error) {
                $("#showError").text(error.message);
                $("#showError").show();
            });
        }

        function verifyPhoneNumber() {
            var code = $("#verfifyNumber").val();
            coderesult.confirm(code).then(function (res) {
                var user = res.user;
                alert(user);
                $("#otpSuccess").text("Auth successful");
                $("#otpSuccess").show();
            }).catch(function (error) {
                $("#showError").text(error.message);
                $("#showError").show();
            });
        }
    </script>
</body>

</html>

Our phone number authentication module is simple; It has two simple input fields and a Google ReCaptcha module. The first input box is for taking the user’s phone number and a Recapthca for spam protection; another input box is to verify the OTP (One-time password).

Use bootstrap 5 to style the component; if you want to add custom style, then go for it.

View App in Browser

We are ready to see how to perform the authentication using phone number in laravel with firebase auth provider, execute command run the laravel app.

php artisan serve

Here is the url, you can use locally to view your app.

http://127.0.0.1:8000/firebase-auth

Laravel Firebase Phone Number OTP Auth Guide

Conclusion

In this quick guide, we explained even the tiny information to build phone number auth in laravel; we looked into every detail, be it laravel or Firebase.

Also, we taught you how to use bootstrap 5 to design the phone auth form. We hope you have understood how to build mobile number authentication in Laravel using Firebase.