Web Push Notification Send Using Firebase Cloud Messaging In Laravel Tutorial Include Demo Example

  • 01-07-2022
  • 10854
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

In this, we will learn how to send a laravel Firebase push notification (FCM) tutorial example. This is throughout comprehensive laravel with Firebase web pus notification demo example, we will learn you how to send web push notifications in the laravel application using Firebase.

Notification is one type of message that is received by the client-side in real-time on the mobile device on that application and web browser. It will through the message to the client-side real-time on the screen.

The push notification is purposed to notify the user in real-time to remember a top of the offer or some important message like offer due.

So in this tutorial, you will learn how to send web push notifications using Firebase cloud messaging in the laravel app.

For web push notifications we need to take the help of javascript node and ajax for the server requesting.

Firebase is an important bass that refers to backend setup as services. it comes will the power tool to build modern web and mobile applications, The Firebase cloud messaging (FCM) it makes easy to integrate into the site and some quick solutions for it. easy guidelines and fast sending notification to we b and mobile application.

This (FCM) provides fee and open source services to send a notification across many devices. Firebase cloud messaging is also knows as FCM.

So let's start integration in the laravel application and send a notification to the web browser.

Step 1: Create Laravel Project

If you already working on an existing project, just skip this step and go to next step.

First, We will clone a new fresh laravel project using the composer command, make sure you installed composer in your system.

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

Hit the above command in your terminal and create a laravel new project.

Step 2: Get Into The Project Directory

Goto in your project directory using the below path press in your terminal.

cd push_notification_example 

Step 3: Database Connection

After going to your directory we must need to connect our database server with this laravel application.

So if you are MYSQL then to go localhost/phpmyadmin and create a new database.


Step 4: Add Device Token Column

After connection, we need to add a column name device_token in the user's table.

For adding the device token column in the user's table need to create a migration. Let's create migration with the below command.


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

class CreateUsersTable extends Migration
        * Run the migrations.
        * @return void
    public function up()
        Schema::create('users', function (Blueprint $table) {
            $table->text('device_token')->nullable(); // Add device token in users migration file.

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

Step 5: Add-In Fillable Property

After editing in users migration add this column name attribute in the fillable property in the App/Models/User model.


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;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
    use HasApiTokens, HasFactory, Notifiable;

     * The attributes that are mass assignable.
     * @var array
    protected $fillable = [
        'device_token' // attriiteattribute added

     * The attributes that should be hidden for serialization.
     * @var array
    protected $hidden = [

     * The attributes that should be cast.
     * @var array
    protected $casts = [
        'email_verified_at' => 'datetime',

Step 6: Migrate Table

After adding the device token property to the user model. we need to migrate that tables into our database.

Using the below command all tables will be migrated into the our database.

php artisan migrate

Step 7: Install UI

Next, we have to install the laravel UI package and create some bootstrap and CSS framework. that will provide a ready-made login design.

Hence execute the given below command and install UI package in your laravel application.

composer require laravel/ui

Step 8: Install Bootstrap Auth

After that, you need to execute the following command to manifest bootstrap UI for authentication.

php artisan ui bootstrap --auth

Step 9: npm Install

Afterward, you have to run the below command in your project path root terminal to compile node module in your laravel application.

npm install

This will create node_modules in your laravel directory.

Now it's time to compile your node module. Before that I would like to suggest you just before compiling check the webpack.mix.js file. All paths are given correctly or not.

const mix = require('laravel-mix');

 | Mix Asset Management
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')

After it compiles your application with the node module. Just run the following suggested command in your terminal. it will be done itself. it takes some time to compile it.

npm run dev

Note: It might you ask to install a package npm install resolve-url-loader@^5.0.0 --save-dev --legacy-peer-deps.

Then After run again this command npm run dev

Step 10: Create Project In FCM

This step will give you the server key and app key, appId from firebase clouding messaging.

Go to fireabse Firebase Site and here you need to create a firebase project.


Go to create and coding section mark given in image, click there.


Add the notification app name for adding the firebase app to your web.


After registration configuration keys provide by firebase. This credential will help you to connect the laravel application with firebase.


After registering the firebase project. we need to enable firebase access permission in google console for use it.

Then after enable fireabse permission in google console just click and generate serverkey.


This is for we suggested you to allow access browser notifications.


Step 11: Create a Controller

Now we will create a controller, using the below-suggested command you just copy and past it in your terminal.

php artisan make:controller NotificationSendController

This command will create a controller in your controller's folder inside the app directory.

Step 12: Setting Up Controller

Add all that method in your notification controller.



namespace App\Http\Controllers;

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

class NotificationSendController extends Controller
    public function updateDeviceToken(Request $request)
        Auth::user()->device_token =  $request->token;


        return response()->json(['Token successfully stored.']);

    public function sendNotification(Request $request)
        $url = 'https://fcm.googleapis.com/fcm/send';

        $FcmToken = User::whereNotNull('device_token')->pluck('device_token')->all();
        $serverKey = 'app-server-key'; // ADD SERVER KEY HERE PROVIDED BY FCM
        $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
        // FCM response

Both authentication methods are defined here in the above controller.

Step 13: home.blade.php

Here in this blade file, we required some config as given the below code.


<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
            <div class="card mt-3">
                <div class="card-body">
                    @if (session('status'))
                    <div class="alert alert-success" role="alert">
                        {{ session('status') }}
                    <form action="{{ route('send.web-notification') }}" method="POST">
                        <div class="form-group">
                            <label>Message Title</label>
                            <input type="text" class="form-control" name="title">
                        <div class="form-group">
                            <label>Message Body</label>
                            <textarea class="form-control" name="body"></textarea>
                        <button type="submit" class="btn btn-success btn-block">Send Notification</button>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.2/firebase.js"></script>
    var firebaseConfig = {
        apiKey: "api-key",
        authDomain: "auth-domian",
        databaseURL: 'db-url',
        projectId: "project-id",
        storageBucket: "storage-bucket",
        messagingSenderId: "message-sender-id",
        appId: "app-id",
        measurementId: "measurement-id"
    const messaging = firebase.messaging();
    function startFCM() {
            .then(function () {
                return messaging.getToken()
            .then(function (response) {
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    url: '{{ route("store.token") }}',
                    type: 'POST',
                    data: {
                        token: response
                    dataType: 'JSON',
                    success: function (response) {
                        alert('Token stored.');
                    error: function (error) {
            }).catch(function (error) {
    messaging.onMessage(function (payload) {
        const title = payload.notification.title;
        const options = {
            body: payload.notification.body,
            icon: payload.notification.icon,
        new Notification(title, options);

Step 14: public/firebase-messaging-sw.js

Create a js file inside the public folder with the name firebase-messaging-sw.js.

These file contents were already provided by firebase cloud messaging when you registered your app on it. So paste here that provided code here.

// 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');
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
    apiKey: "api-key",
    authDomain: "auth-domian",
    databaseURL: 'db-url',
    projectId: "project-id",
    storageBucket: "storage-bucket",
    messagingSenderId: "message-sender-id",
    appId: "app-id",
    measurementId: "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(

Step 15: Define Routes

The default home route is already there, It is created when you push the auth command in your terminal. earlier in this step given.

After it we will create an auth group of middleware, In this group, we will define two routes. the first route is for updating the device token in the user's table and the second route is for sending web push notifications.

To use that created controller you need to use your route file web.php


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\NotificationSendController;
| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!


Route::get('/home', [HomeController::class, 'index'])->name('home');

Route::group(['middleware' => 'auth'],function(){
    Route::post('/store-token', [NotificationSendController::class, 'updateDeviceToken'])->name('store.token');
    Route::post('/send-web-notification', [NotificationSendController::class, 'sendNotification'])->name('send.web-notification');

Both auth group route methods will be posted.

Step 16: Run & Test

Web push notification using firebase cloud messaging, Now it's time to test, Finally, we send notification using FCM in laravel application so need to run project apply a command PHP artisan command with serve to start the laravel development server.

php artisan serve

Once the app starts, Register a new user.

After Registering you need to log in that registered user.

After signing in, then follow the below-given URL.

Next, you need to click on the allow notification button, it will update the device token from your browser and update into authentication user.

After you received alert token stored Filed input given title and body. The title will be your notification title and body will be your notification message.


Once You clicked on Send Notification Button It will send a web push notification.



Firebase Notification Send Example - PHP

So this is the simple process to send web push notifications using firebase cloud messaging in the laravel app.

We always thanks to you for reading our blogs.


Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us


Haresh Chauhan


We Are Also Recommending You :