Laravel 10 Send Web Push Notification with Firebase Tutorial

Last Updated on by in Laravel

Laravel Firebase push notification tutorial; Throughout this comprehensive Laravel Firebase web push notification example, we will explain how to send web push notifications in the Laravel app using Firebase Cloud Messaging mechanism.

A push notification is a message that appears on a mobile device and a web app. Push notifications provide a great way to communicate with customers or users regarding any context.

In this tutorial, we will learn how to easily send web push notifications from the Laravel app using Firebase and gradually elevate the customer experience and add value to the product’s user experience.

Firebase is an awesome BaaS that refers to the backend as a service; it comes with powerful tools to build modern web and mobile applications. It makes the development process easy through its vast array of user-centric features.

To send Firebase web push notifications, we need to get the Firebase SDK or configuration key through which we can manage the app’s data on a centralized cloud platform.

Firebase cloud messaging offers a free service to send a notification across any device, and Firebase Cloud Messaging is also known as FCM. It gives a reliable and robust battery-efficient connection among your server and devices that empowers you to deliver and receive messages and notifications on iOS, Android, and the web.

To create a push notification, we need to acquire the server key or token from the firebase dashboard and add this token into the laravel app to send web push notifications.

So, let us go through one by one every instruction mentioned below.

How to Send Web Push Notifications in Laravel 10 using Firebase

  • Step 1: Create Laravel Project
  • Step 2: Database Connection
  • Step 3: Install Laravel UI Scaffolding
  • Step 4: Update Server Key Prop in User Table
  • Step 5: Get Firebase Cloud Messaging Server Key
  • Step 6: Create Controller
  • Step 7: Create Routes
  • Step 8: Set Up Blade View
  • Step 9: Create Firebase (FCM) File
  • Step 10: Run Laravel App

Create Laravel Project

Let us start creating a fresh new laravel app using the composer command, so make sure to configure composer on your system.

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

Get into the app’s root:

cd laravel_web_push_notification

Database Connection

Secondly, add database name, username and password in the .env file to make the database connection:

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Install Laravel UI Scaffolding

Next, we have to install the laravel ui package and create auth scaffolding based on Bootstrap CSS framework, hence execute the given below commands.

composer require laravel/ui

After that, you need to execute the following command to manifest bootstrap auth ui.

php artisan ui bootstrap --auth

Afterward, you have to run suggested commands to compile your fresh scaffolding.

npm install && npm run dev

Update Server Key Prop in User Table

Subsequently, we need to add the new column property in the current User table inside the database, execute the below command.

php artisan make:migration add_column_device_key

After that, you have to move to database/migrations/xxxx_add_column_device_key.php
file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddColumnDeviceKey extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('device_key')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

After that, move to the app/Models/User.php file and add the device key property.

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'device_key',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Head over to the terminal, type the following command, and execute it to run the migration.

php artisan migrate

Get Firebase Cloud Messaging (FCM) Server Key

This step will describe how to get the Firebase cloud messaging server key and Firebase web app’s configuration credentials.

So, first go to Firebase site and here you need to create a Firebase project.

create firebase project

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

add the notification app

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

Firebase configuration keys

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 the $serverKey variable. That is defined in the web notification controller file’s sendWebNotification() function.

Create Controller

We need to create some functions in the controller file to handle web notifications, so first generate the controller.

php artisan make:controller WebNotificationController

Open and place the suggested code inside the app\Http\Controllers\WebNotificationController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class WebNotificationController extends Controller
{
  
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }
  
    public function storeToken(Request $request)
    {
        auth()->user()->update(['device_key'=>$request->token]);
        return response()->json(['Token successfully stored.']);
    }
  
    public function sendWebNotification(Request $request)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        $FcmToken = User::whereNotNull('device_key')->pluck('device_key')->all();
          
        $serverKey = 'server key goes here';
  
        $data = [
            "registration_ids" => $FcmToken,
            "notification" => [
                "title" => $request->title,
                "body" => $request->body,  
            ]
        ];
        $encodedData = json_encode($data);
    
        $headers = [
            'Authorization:key=' . $serverKey,
            'Content-Type: application/json',
        ];
    
        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);

        // Execute post
        $result = curl_exec($ch);

        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }        

        // Close connection
        curl_close($ch);

        // FCM response
        dd($result);        
    }
}

Create Routes

Import WebNotificationController controller, then create three routes with Get and Post methods, so open and place the code in routes/web.php file.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Auth::routes();

Route::get('/push-notificaiton', [WebNotificationController::class, 'index'])->name('push-notificaiton');
Route::post('/store-token', [WebNotificationController::class, 'storeToken'])->name('store.token');
Route::post('/send-web-notification', [WebNotificationController::class, 'sendWebNotification'])->name('send.web-notification');

Set Up Blade View

This step comprises setting up the home blade view file, integrate push notification code for the web app hence open resources/views/home.blade.php file, and replace with the following code.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">

                <button onclick="startFCM()"
                    class="btn btn-danger btn-flat">Allow notification
                </button>

            <div class="card mt-3">
                <div class="card-body">
                    @if (session('status'))
                    <div class="alert alert-success" role="alert">
                        {{ session('status') }}
                    </div>
                    @endif

                    <form action="{{ route('send.web-notification') }}" method="POST">
                        @csrf
                        <div class="form-group">
                            <label>Message Title</label>
                            <input type="text" class="form-control" name="title">
                        </div>
                        <div class="form-group">
                            <label>Message Body</label>
                            <textarea class="form-control" name="body"></textarea>
                        </div>
                        <button type="submit" class="btn btn-success btn-block">Send Notification</button>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.3.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);
    const messaging = firebase.messaging();

    function startFCM() {
        messaging
            .requestPermission()
            .then(function () {
                return messaging.getToken()
            })
            .then(function (response) {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $.ajax({
                    url: '{{ route("store.token") }}',
                    type: 'POST',
                    data: {
                        token: response
                    },
                    dataType: 'JSON',
                    success: function (response) {
                        alert('Token stored.');
                    },
                    error: function (error) {
                        alert(error);
                    },
                });

            }).catch(function (error) {
                alert(error);
            });
    }

    messaging.onMessage(function (payload) {
        const title = payload.notification.title;
        const options = {
            body: payload.notification.body,
            icon: payload.notification.icon,
        };
        new Notification(title, options);
    });

</script>
@endsection

Create Firebase (FCM) File

In the final step, we have to create head over to a public folder and create a new firebase-messaging-sw.js file; this file holds the web push notification configurations.

So, after creating the file, add the given below code in the public/firebase-messaging-sw.js file.

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js');

/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
*/
firebase.initializeApp({
    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',
});


// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
    console.log("Message received.", payload);

    const title = "Hello world is awesome";
    const options = {
        body: "Your notificaiton message .",
        icon: "/firebase-logo.png",
    };

    return self.registration.showNotification(
        title,
        options,
    );
});

Send FCM Web Push Notification in Laravel

Finally, we have to send the push notification in Laravel using FCM, so we need to execute the php artisan command with serve flag to start the laravel development server.

php artisan serve

Once the app is started, make sure to register a new user. After creating a new account then you have to login into the app using your email and password.

# Register new user
http://127.0.0.1:8000/register


# Sign-in to account
http://127.0.0.1:8000/login

After, you signed-in, then head over to following url:

http://127.0.0.1:8000/push-notificaiton

Next, you need to click on the allow notification button, it will generate the device id, also add push notification title and body in the given form.

Laravel FCM Web Push Notification

Here is the response for web push notification sent by you on the browser:

FCM web push notification response

Conclusion

The laravel push notification example is finished; we have described how to send web push notifications in laravel using the Firebase database. We exclusively understood how to connect Firebase cloud messaging (FCM) with Laravel to send notification.

Here is the complete code example that you can download from GitHub.