Have any questions:

Toll free:9801887718Available 24/7

Email our experts:info@mantraideas.com

In: Web Development

Push notifications are one of the most effective ways to re-engage users in modern applications. Whether you are building a mobile app, OTT platform, eCommerce system, or admin dashboard, real-time notifications help deliver updates instantly.

In this guide, we will integrate Firebase Cloud Messaging (FCM) into a Laravel application using a clean and maintainable approach. Instead of manually handling the entire Firebase SDK setup, we’ll use a Laravel-friendly package to simplify authentication and communication with Firebase services.

The core notification logic can vary depending on your project requirements, so this article focuses on the setup, structure, configuration, and integration flow.

Why Use Firebase Cloud Messaging?

Firebase Cloud Messaging is a free service by Google that allows you to send notifications to Android, iOS, and web applications.

Some common use cases include:

  • Order status updates
  • New message alerts
  • Marketing campaigns
  • Live streaming notifications
  • System announcements
  • Reminder notifications

Firebase handles the infrastructure, scalability, and delivery reliability, allowing developers to focus on application logic.

Why Use a Laravel Package?

Directly integrating Firebase APIs can become repetitive and difficult to maintain. A Laravel package helps with:

  • Authentication handling
  • Service account integration
  • Cleaner API structure
  • Better Laravel ecosystem support
  • Easier testing and maintenance

For this integration, we’ll use devkandil/notifire package.

Prerequisites

Before starting, make sure you have:

  • A Laravel application
  • A Firebase project
  • PHP and Composer installed
  • Access to Firebase Console
  • Push notification tokens from client devices

Step 1: Create a Firebase Project

Go to the Firebase Console and create a new project.

Inside the project dashboard:

  1. Open Project Settings
  2. Navigate to Service Accounts
  3. Generate a new private key
  4. Download the JSON credentials file

This file will be used by Laravel to authenticate with Firebase services.

Step 2: Install the Firebase Package

Run the following Composer command:

composer require devkandil/notifire

After installation, publish the configuration file:

# Publish everything
php artisan vendor:publish --provider="DevKandil\NotiFire\FcmServiceProvider"

# Or publish specific components
php artisan vendor:publish --tag=fcm-config
php artisan vendor:publish --tag=fcm-migrations
php artisan vendor:publish --tag=fcm-notifications
php artisan vendor:publish --tag=fcm-contracts
php artisan vendor:publish --tag=fcm-enums
php artisan vendor:publish --tag=fcm-traits

Step 3: Configure Environment Variables

Store your Firebase credentials securely.

Example:

# Required: Your Firebase project ID from the Firebase Console
FIREBASE_PROJECT_ID=your-project-id

You may also configure additional Firebase services depending on your application needs. For notifications this configuration is enough.

Avoid committing Firebase credential files to version control.

Step 4: Migration And Other Configuration

Place your Firebase service account credentials JSON file in your Laravel storage directory:

/storage/firebase.json

Run the migration:

php artisan migrate

Step 5: Make Your Model Ready

<?php

namespace App\Models;

use Database\Factories\UserFactory;
use DevKandil\NotiFire\Traits\HasFcm;
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 implements MustVerifyEmail
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable, HasFcm;

    protected $fillable = [
        // existing fields...
        'fcm_token',
    ];
}

The HasFcm trait provides the required Firebase notification functionality for your model.This allows Laravel notifications to automatically communicate with Firebase Cloud Messaging.

Sending Notifications Using the Facade

For simple use cases, the package provides a clean facade interface.

Simple Notification

<?php

use DevKandil\NotiFire\Facades\Fcm;

$success = Fcm::withTitle('Hello')
    ->withBody('This is a test notification')
    ->sendNotification($fcmToken);

if ($success) {
     // Notification sent successfully
}

Advanced Notification

<?php

use DevKandil\NotiFire\Enums\MessagePriority;
use DevKandil\NotiFire\Facades\Fcm;

$fcmToken = 'your_fcm_token';

$success = Fcm::withTitle('Hello')
    ->withBody('This is a test notification')
    ->withImage('https://example.com/image.jpg')
    ->withIcon('notification_icon')
    ->withColor('#FF5733')
    ->withSound('default')
    ->withPriority(MessagePriority::HIGH)
    ->withAdditionalData(['key' => 'value'])
    ->sendNotification($fcmToken);

if ($success) {
    // Notification sent successfully
}

Sending Topic Notifications

Send to a Single Topic

<?php

use DevKandil\NotiFire\Facades\Fcm;

$success = Fcm::withTitle('News Update')
    ->withBody('Breaking news just dropped!')
    ->sendToTopics('news');

Send to Multiple Topics

<?php

use DevKandil\NotiFire\Facades\Fcm;

$topics = ['users', 'updates'];

$success = Fcm::withTitle('Hello')
    ->withBody('This is a test notification')
    ->sendToTopics($topics);

Topic-based notifications are extremely useful for:

  • Marketing campaigns
  • Category subscriptions
  • News alerts
  • Sports updates
  • Live events
  • Regional announcements

Creating a Dedicated Firebase Notification Class

While sending notifications directly using the Fcm facade works perfectly for simple use cases, larger applications usually benefit from Laravel’s native notification system.

Using a dedicated notification class provides:

  • Better code organization
  • Queue support
  • Reusable notification templates
  • Cleaner business logic
  • Easier testing and maintenance

This approach becomes especially useful when your application sends multiple notification types such as:

  • Order updates
  • Chat messages
  • Marketing campaigns
  • OTP notifications
  • System alerts

Creating the Notification Class

Generate a Laravel notification:

php artisan make:notification FirebaseNotification

Now update the notification class:

<?php

namespace App\Notifications;

use DevKandil\NotiFire\Enums\MessagePriority;
use DevKandil\NotiFire\FcmMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class FirebaseNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct(
        public string $title,
        public string $body,
    ) {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['fcm'];
    }

    /**
     * Get the FCM representation of the notification.
     */
    public function toFcm(object $notifiable): FcmMessage
    {
        return FcmMessage::create($this->title, $this->body)
            ->priority(MessagePriority::HIGH)
            ->data([
                'timestamp' => now()->toIso8601String(),
            ]);
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [];
    }
}

Understanding the Notification Structure

Laravel notifications follow a clean channel-based architecture.

In this case:

return ['fcm'];

This tells Laravel to deliver the notification through Firebase Cloud Messaging.

The package automatically handles the communication with Firebase behind the scenes.

Passing Dynamic Notification Data

The constructor allows dynamic titles and messages:

public function __construct(
    public string $title,
    public string $body,
) {
   //
}

This makes the notification reusable across different parts of your application.

Example use cases:

  • Order Shipped
  • New Message Received
  • Subscription Expiring Soon
  • Live Stream Started

Instead of creating separate notification classes for every message type, you can reuse the same structure with different data.

Setting Notification Priority

Inside the toFcm() method:

->priority(MessagePriority::HIGH)

High priority notifications are usually delivered immediately and are ideal for:

  • Chat messages
  • Live alerts
  • Transactional updates
  • Time-sensitive events

Depending on your application, you may also use normal priority for less urgent notifications.

Sending Additional Data

FCM notifications can also carry additional payload data:

->data([
    'timestamp' => now()->toIso8601String(),
]);

This is extremely useful for frontend applications.

For example, mobile apps may use this data to:

  • Open a specific screen
  • Refresh content
  • Track notification events
  • Handle custom actions
  • Sync real-time updates

Most production applications rely heavily on custom payload data.

Sending Notifications to Users

Once the notification class is ready, sending notifications becomes very clean.

Example:

use App\Notifications\FirebaseNotification;

$user->notify(
    new FirebaseNotification(
        title: 'Order Confirmed',
        body: 'Your order has been successfully placed.'
    )
);

Laravel will automatically route the notification through Firebase.

Why Queue Notifications?

Push notification delivery should almost always be queued in production applications.

This notification already implements:

implements ShouldQueue

Which means Laravel will automatically send it through the queue system.

Benefits of queues:

  • Faster request handling
  • Better scalability
  • Reduced server load
  • Automatic retry support
  • Improved user experience

Without queues, notification delivery can slow down API responses significantly.

Configuring Laravel Queues

Before using queued notifications, configure your queue driver.

Example .env configuration:

QUEUE_CONNECTION=database

Create the jobs table:

php artisan queue:table
php artisan migrate

Start the queue worker:

php artisan queue:work

For production servers, you should use process managers like Supervisor to keep queue workers running continuously.

Queue Best Practices

For larger applications:

  • Separate notification queues from heavy jobs
  • Monitor failed jobs
  • Retry temporary failures
  • Use queue batching for bulk notifications
  • Track notification delivery logs

As notification volume increases, queue architecture becomes extremely important.

Handling Device Tokens

The mobile or frontend application is responsible for generating Firebase device tokens.

Your Laravel backend should:

  • Save tokens securely
  • Remove invalid tokens
  • Update refreshed tokens
  • Prevent duplicate entries

Token management is one of the most important parts of a reliable push notification system.

Notification Types You Can Build

Once Firebase is integrated, you can create different types of notifications.

Transactional Notifications

Used for important user actions:

  • OTP verification
  • Order updates
  • Account activity alerts

Marketing Notifications

Used for engagement:

  • Promotions
  • New content alerts
  • Product announcements

Real-Time Event Notifications

Used for live systems:

  • Chat messages
  • Live stream alerts
  • System events

Security Best Practices

When integrating Firebase into Laravel, keep these best practices in mind:

  • Never expose Firebase credentials publicly
  • Use environment variables properly
  • Validate notification requests
  • Limit admin notification access
  • Monitor notification abuse
  • Use queues for mass delivery

Common Issues Developers Face

Invalid Registration Token

Usually caused by expired or malformed device tokens.

Notifications Not Received

Common causes include:

  • App notification permissions disabled
  • Incorrect Firebase configuration
  • Background restrictions on devices

Firebase Authentication Errors

Often related to:

  • Incorrect credential path
  • Invalid JSON key file
  • Permission issues

Scaling Push Notifications

As your application grows, you may need:

  • Topic-based notifications
  • Bulk notification processing
  • Segmented audiences
  • Scheduled campaigns
  • Analytics tracking

Firebase supports these features and integrates well with scalable Laravel architectures.

Recommended Architecture

A clean notification flow usually looks like this:

User Action
 ↓
Event / Service Class
 ↓
Laravel Notification
 ↓
Queue
 ↓
Firebase Cloud Messaging
 ↓
Mobile / Web Device

This architecture works extremely well for scalable Laravel applications.

Final Thoughts

Firebase Cloud Messaging is one of the easiest and most scalable ways to implement push notifications in Laravel applications.

Using a dedicated Laravel package keeps the integration clean and maintainable while allowing you to build your own custom notification logic on top of it.

Once the setup is complete, you can extend the system to support:

  • Mobile applications
  • Web push notifications
  • Admin panel alerts
  • Marketing automation
  • Real-time engagement systems

The actual notification logic depends on your application architecture, but the foundation remains largely the same across projects.

Happy coding 🚀

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *