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

  • 01-07-2022
  • 13528
  • 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.

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

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.

<?php

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->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->text('device_token')->nullable(); // Add device token in users migration file.
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
        * Reverse the migrations.
        *
        * @return void
        */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

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.

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

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

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

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

    /**
     * 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')
    .sourceMaps();

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.

image

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

image

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

image

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

image

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.

image

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

image

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.

app\Http\Controllers\NotificationSendController.php

<?php

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;

        Auth::user()->save();

        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
        curl_close($ch);
        // FCM response
        dd($result);
    }
}

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.

resources/views/home.blade.php

@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="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>
<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"
    };
    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

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');
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: "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(
        title,
        options,
    );
});

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

routes/web.php

<?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!
|
*/

Auth::routes();

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.

http://127.0.0.1:8000/register

After Registering you need to log in that registered user.

http://127.0.0.1:8000/login

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

http://127.0.0.1:8000/push-notificaiton

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.

image

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

OUTPUT :

image

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-image

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-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :