Laravel 10 Firebase Web Push Notification Tutorial

  • 01-04-2023
  • 7070
  • Laravel 10
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Laravel 10 Firebase Web Push Notification Tutorial Example; In this comprehensive post we will integrate firebase web push notification in laravel 10, I will tell you to step by step guidelines for integration as well as how to generate credentials and services key id from firebase I will tell you in this post.

Integration push notification in laravel integration is the most challenging part for beginner and intermediate developers who just started learning laravel. In this article, I will tell you all the step-by-step integration process to apply firebase web push notifications in your laravel app.

Firebase Web push notification when required, you app e-commerce and want to market a related offer or any sale or discount offer that you want to inform your users that time must need push notification via that we call to inform our users.

Laravel web push notifications example in laravel in this article we will see step by step process, So In your mind question how to integrate firebase web push notification? this article will help you.

Step 1: Create Laravel 10 Project

We will create a new fresh laravel 10 project, skip this step if you already installed the project. For installing laravel 10 you must need php 8 or greater version for the support laravel 10 composer package library. So if you don't install the php 8 version first update your php version and install the new laravel 10 app.

composer create-project laravel/laravel laravel10

We will go to the app directory, use "cd" given your app directory name, and hit enter. your terminal will go to your app path. This is for pressing some commands.

cd laravel10

Step 2: Database Connection

Now we will config the database. so open your database and create a database. Skip this step if your app is already connected to the database. This step is for those who start implementing we b push notifications from scratch. So make your database connection.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=web_pushnotification
DB_USERNAME=root
DB_PASSWORD=root

Step 3: Add Device Token Column

Add a "device_token" column in your user's migration, in this column we will add a user web browser token so we can identify your browser and able to send a notification. So add that column with text datatype migration. In this step that's it.

database/migrations/2014_10_12_000000_create_users_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        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.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

Now, we will add the "device_token" column attribute name in the fillable array property in the User.php model. So open your User model and add this "device_token" property in the fillable property.

App\Models\User.php
<?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'
    ];

    /**
     * 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',
    ];
}

After that, we will migrate our database. Use the below command and migrate our migration all tables in the database. Add this command to your app terminal and hit enter. This will migrate your app to all tables in your database.

php artisan migrate

Step 4: 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 the UI package in your laravel application.

composer require laravel/ui

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

php artisan ui bootstrap --auth

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

This will create node_modules in your laravel directory.

npm install

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 5: 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 6: Create a Controller

Now we will create a controller, using the below-suggested command you just copy and past it in your terminal. This command will create a controller in your controller's folder inside the app directory.

php artisan make:controller NotificationSendController

Add all that method in your notification controller.

app\Http\Controllers\NotificationSendController.php
<?php

namespace App\Http\Controllers;

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

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 = 'AAAAeypmfso:APA91bE_G5v_1ua1165UpBrauhCBRUxQO-aPcXpOpLAhDhnggX6OU7ACoDRRwY6JNZbH6YQYs_FxAJL3FkD4FQZDYKkFeoHZXJGLUTzDe17uk3gwgVwmzWol1xOb11SIsov_TWrPXd3m'; // 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 7: Blade File

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: "AIzaSyCkj1gm3aYruqct9F6DvkshEMOBIkyECrY",
        authDomain: "notification-3b471.firebaseapp.com",
        projectId: "notification-3b471",
        storageBucket: "notification-3b471.appspot.com",
        messagingSenderId: "528992337610",
        appId: "1:528992337610:web:2872ce8029c36ffbc07e33",
        measurementId: "G-8HJ6Y9RGG1"
    };
    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 8: 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: "AIzaSyCkj1gm3aYruqct9F6DvkshEMOBIkyECrY",
    authDomain: "notification-3b471.firebaseapp.com",
    projectId: "notification-3b471",
    storageBucket: "notification-3b471.appspot.com",
    messagingSenderId: "528992337610",
    appId: "1:528992337610:web:2872ce8029c36ffbc07e33",
    measurementId: "G-8HJ6Y9RGG1"
});

// 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 9: 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\NotificationSendController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\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 10: 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

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 :