Laravel 9 Firebase Mobile Phone Number Verification Example Tutorial

Laravel Mobile Mumber OTP verification using Firebase Example; In this step by step tutorial, we are going to share how to create Phone or mobile number OTP authentication in Laravel using the Firebase.

Firebase provides a realtime database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients and stored on Firebase’s cloud. Let us start implementing the firebase phone auth in the laravel app.

Karavel OTP verification using Firebase

Follow the following steps to integrate Phone Number OTP Authentication in laravel application using Firebase Example;

  • Step 1: Create Firebase Project
  • Step 2: Enable Firebase Phone Auth
  • Step 3: Install Laravel App
  • Step 4: Connecting App to Databasee
  • Step 5: Add Route
  • Step 6: Create Controller
  • Step 7: Set Up Blade View
  • Step 8: Start Development Server

Create Firebase Project

Before starting this tutorial, visit Firebase Console and create a project. then have to create web app on that project as like below screenshot:

laravel-firebase-push-notification

Then, add the notification app name for adding Firebase to your web app.

laravel-firebase-push-notification-example-create app

Copy the Firebase configuration keys, and this will help to connect laravel to Firebase.

laravel firebase mobile number varification

Get into the Firebase project dashboard in the “Settings” page, click on the “Cloud Messaging” tab. You need to look for the “Server key”, copy this cloud messaging server key, and you have to paste this key in your env file.

Enable Firebase Phone Auth

The Firebase project has been created. Now you have to enable the firebase phone authentication, click on the authentication tab, head over to the Sign-in method section, click on the Phone item and enable the Phone auth.

Install Laravel App

First create a fresh laravel app using the composer command:

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

Get into the app’s root:

cd laravel-web-notification

Connect App to Database

Update your add database name, username and password in the .env file for database connectivity:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Add Route

In this step, open web.php, so navigate to routes directory. And then add the following routes for mobile otp varification:

routes/web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PhoneAuthController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('phone-auth', [PhoneAuthController::class, 'index']);

Create Controller

Open terminal, type command, then execute the command that generates a new controller; in this controller we will call the blade view for showing the mobile otp auth form.

php artisan make:controller PhoneAuthController

Open and add code in app/http/controllers/PhoneAuthController.php file:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PhoneAuthController extends Controller
{
    public function index(){
      return view('firebase');
    }
}

Create Blade View File

Now create an firebase.blade.php blade view file inside resources/views directory. Open and replace with the following code in resources/views/firebase.blade.php:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 Phone Number OTP Auth Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5" style="max-width: 550px">
        <div class="alert alert-danger" id="error" style="display: none;"></div>
        <h3>Add Phone Number</h3>
        <div class="alert alert-success" id="successAuth" style="display: none;"></div>
        <form>
            <label>Phone Number:</label>
            <input type="text" id="number" class="form-control" placeholder="+91 ********">
            <div id="recaptcha-container"></div>
            <button type="button" class="btn btn-primary mt-3" onclick="sendOTP();">Send OTP</button>
        </form>

        <div class="mb-5 mt-5">
            <h3>Add verification code</h3>
            <div class="alert alert-success" id="successOtpAuth" style="display: none;"></div>
            <form>
                <input type="text" id="verification" class="form-control" placeholder="Verification code">
                <button type="button" class="btn btn-danger mt-3" onclick="verify()">Verify code</button>
            </form>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
    <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"
        };
        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 sendOTP() {
            var number = $("#number").val();
            firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function (confirmationResult) {
                window.confirmationResult = confirmationResult;
                coderesult = confirmationResult;
                console.log(coderesult);
                $("#successAuth").text("Message sent");
                $("#successAuth").show();
            }).catch(function (error) {
                $("#error").text(error.message);
                $("#error").show();
            });
        }
        function verify() {
            var code = $("#verification").val();
            coderesult.confirm(code).then(function (result) {
                var user = result.user;
                console.log(user);
                $("#successOtpAuth").text("Auth is successful");
                $("#successOtpAuth").show();
            }).catch(function (error) {
                $("#error").text(error.message);
                $("#error").show();
            });
        }
    </script>
</body>
</html>

Start Your Application

Finally, open command prompt and run the following command to start developement server:

php artisan serve

Then open browser and hit the following url on it:

http://127.0.0.1:8000/phone-auth

So, today you have learned how to authenticate with mobile number OTP in Laravel with Firebase. It is easy to add firebase authentication to login into a user by sending a one-time SMS message to the user’s mobile number.