How to Send Web Push Notification in Laravel 9 with Firebase

Web push notifications or browser notifications are the best way to keep your website visitors informed about the status of your product or service, and that too even without installing your app.

In this Laravel Firebase push notification guide, you will study how to send web push notification from the laravel app using Firebase.

We will show you uncomplicated methods, which will help you get into the core of the laravel firebase web push notification topic and help you build the entire laravel send push notification firebase system from scratch.

Firebase push notification service is powered by Firebase Cloud Messaging service; it is super awesome; we will show you how to integrate Firebase browser push notification in laravel.

You need a Gmail account to create the Firebase project, a basic laravel app with some tiny configurations and most importantly, a device token of logged-in users. These are ingredients will help us send web push notification.

After finishing up this firebase push notification laravel tutorial, you will clearly understand the example of integrating firebase push notification in laravel application from scratch.

Laravel 9 Firebase Cloud Messaging Push Notification Example

  • Step 1: Download Laravel App
  • Step 2: Connect to MySQL Database
  • Step 3: Create Firebase SDK + FCM (Firebase Cloud Messaging) Server ID
  • Step 4: Add Device Key in Table
  • Step 5: Set Up Laravel UI in Laravel
  • Step 6: Set Up New Controller
  • Step 7: Register New Routes
  • Step 8: Add Firebase Cloud Messaging File in Laravel
  • Step 9: Integrate Send Push Notification in Blade View
  • Step 10: Run Laravel App

Download Laravel App

Let’s lay the foundation of this detailed guide by downloading a new laravel application.

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

Create Firebase SDK + FCM (Firebase Cloud Messaging) Server ID

In order to start with Firebase push notification, you need to create a firebase project for obtaining the Firebase SDK, likewise activate the Firebase cloud messaging service to get the server key.

Land on the firebase.google.com. Use your gmail id to sign up and start creating a firebase project:

Firebase Create Account

Then, define a project name.

Create a project

Likewise, add Firebase to your app:

add Firebase to app

Further, define a project name and include Firebase to your web app:

add firebase

After that, get these Firebase SDK key, we will need it to connect laravel to firebase.

Firebase configuration keys

Get to Project Settings page > Cloud Messaging, look for Project credentials and grab the Server key, in the subsequent step we will set it with $FcmKey variable in the controller file.

Firebase Messaging Server Key

Connect to MySQL Database

Further, add database credentials in the .env file and set up connection between Laravel and MySQL database.

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

Add Device Key in Table

The given command allows adding a new column into the table for the device token or key.

php artisan make:migration add_column_device_token

Update the database/migrations/add_column_device_token.php with device token property.

<?php

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

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

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

Open app/Models/User.php, similarly update the device_token value into the fillable array.

<?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_token',
    ];

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

Next run the provided command to migrate the users table into the database.

php artisan migrate

Set Up Laravel UI in Laravel

This laravel push notification example needs user registration and login pages; you must authenticate to send push notification. Here comes the Laravel UI in play; this will give you pre-cooked auth templates.

composer require laravel/ui

Further, generate the auth scaffolding using the provided command.

php artisan ui bootstrap --auth

Authentication scaffolding have successfully generated. You are all set, to execute the next command to compile the scaffolding.

npm install && npm run dev

Set Up New Controller

Laravel works on the MVC pattern; likewise, all the business logic goes into the controller, go ahead and create a new controller file.

php artisan make:controller UserController

Above command has generated app\Http\Controllers\UserController.php, now in this file you need to define couple of functions which will take care of web notifications.

<?php

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


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

    public function index()
    {
        return view('home');
    }
  
    public function saveDeviceToken(Request $request)
    {
        auth()->user()->update(['device_token'=>$request->token]);
        return response()->json(['Token stored.']);
    }
  
    public function sendNotification(Request $request)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        $DeviceToekn = User::whereNotNull('device_token')->pluck('device_token')->all();
          
        $FcmKey = 'FIREBASE FCM KEY';
  
        $data = [
            "registration_ids" => $DeviceToekn,
            "notification" => [
                "title" => $request->title,
                "body" => $request->body,  
            ]
        ];

        $RESPONSE = json_encode($data);
    
        $headers = [
            'Authorization:key=' . $FcmKey,
            'Content-Type: application/json',
        ];
    
        // CURL
        $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);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $RESPONSE);

        $output = curl_exec($ch);
        if ($output === FALSE) {
            die('Curl error: ' . curl_error($ch));
        }        
        curl_close($ch);
        dd($output);        
    }
}

Register New Routes

To make the controller work, you need routes to define routes land into the routes/web.php and define routes.

<?php

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

/*
|--------------------------------------------------------------------------
| 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('/send-web-push-notificaiton', [UserController::class, 'index'])->name('send-push.notificaiton');

Route::post('/save-device-token', [UserController::class, 'saveDeviceToken'])->name('save-device.token');
Route::post('/send-notification', [UserController::class, 'sendNotification'])->name('send.notification');

Auth::routes();

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

Add Firebase Cloud Messaging File in Laravel

In this section, we will set up the firebase configuration file for web push notification, create the public/firebase-messaging-sw.js and place the provided code in the file.

// Add Firebase products that you want to use
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js');

// Firebase SDK
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',
});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
    console.log("Message has received : ", payload);
    const title = "First, solve the problem.";
    const options = {
        body: "Push notificaiton!",
        icon: "/icon.png",
    };
    return self.registration.showNotification(
        title,
        options,
    );
});

Integrate Send Push Notification in Blade View

In this section, you have to set up the view for the push notification module, get into the resources/views/home.blade.php file, and relentlessly add the provided code into the file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
                <button onclick="initNotification()"
                    class="btn btn-danger btn-flat">Generate Device Token
                </button>
            <div class="card mt-3">
                <div class="card-body">
                    @if (session('status'))
                    <div class="alert alert-success">
                        {{ session('status') }}
                    </div>
                    @endif
                    <form action="{{ route('send.notification') }}" method="POST">
                        @csrf
                        <div class="form-group">
                            <label>Title</label>
                            <input type="text" name="title" class="form-control" >
                        </div>

                        <div class="form-group">
                            <label>Body</label>
                            <textarea name="body" class="form-control" ></textarea>
                        </div>
                        
                        <div class="form-group">
                          <button type="submit" class="btn btn-dark btn-block">Send</button>
                        </div>  
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Firebase App (the core Firebase 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',
    };

    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();

    function initNotification() {
        messaging
            .requestPermission().then(function () {
                return messaging.getToken()
            }).then(function (response) {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $.ajax({
                    url: '{{ route("save-device.token") }}',
                    type: 'POST',
                    data: {
                        token: response
                    },
                    dataType: 'JSON',
                    success: function (response) {
                        console.log('Device token saved.');
                    },
                    error: function (error) {
                        console.log(error);
                    },
                });
            }).catch(function (error) {
                console.log(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

Run Laravel App

In the last section, we will demonstrate how to send web push notifications in laravel using the Firebase cloud messaging service.

Start laravel app using the suggested command.

php artisan serve

First, make sure to create an account using email and password in laravel. The offered urls will take you to user registration and login pages.

# http://127.0.0.1:8000/register

# http://127.0.0.1:8000/login

Ultimately, you are ready to send push notification from laravel; here is the url you need to accomplish the task.

http://127.0.0.1:8000/send-web-push-notificaiton

To send the web notification, add the notification title and description in the input fields, click on generate device token button to store the token and click on send.

Laravel Firebase Web Push Notification Example

Conclusion

Firebase is not limited to storing and managing data in the database; instead, it does plenty of jobs for you.

It comes with loads of features, to build an application it takes less duration, the feature like auth providers, analytics, storage, makes it stand apart really it does so many things.

We went through every instruction and understood how to send firebase push notification in laravel.

We hope we have been helpful throughout the tutorial; and answered honestly regarding how to implement notification in laravel web application. Enjoy life and coding!