Notifier: A Comprehensive Installation and Configuration Guide to integrate Firebase Cloud Messaging (FCM)

In today's mobile-first world, push notifications have become essential for engaging users with timely updates and information. For Laravel developers looking to integrate Firebase Cloud Messaging (FCM) into their applications, the Laravel FCM Notifier package by Abdelrazek Kandil offers an elegant solution that aligns perfectly with Laravel's design philosophy. This comprehensive guide will walk you through setting up and configuring the Notifier package, providing practical examples for all available notification methods. What is Notifier? Notifier is a package that seamlessly integrates Firebase Cloud Messaging with Laravel's notification system. It provides a fluent interface for building notifications, supports both simple and complex FCM messages, automatically logs delivery status, and includes database migrations for storing FCM tokens. Prerequisites Before installing Notifier, ensure you have: A Laravel project (version 8.0 or higher recommended) Composer installed A Firebase project with FCM enabled A service account JSON file from Firebase Step 1: Create a Firebase Project If you don't already have a Firebase project, follow these steps: Go to the Firebase Console Click "Add project" and follow the setup wizard Once your project is created, navigate to Project Settings Click on the "Service accounts" tab Click "Generate new private key" to download your Firebase service account credentials JSON file Make note of your Firebase project ID, which you'll need later Step 2: Install the Package Open your terminal and navigate to your Laravel project directory. Install the package using Composer: composer require devkandil/notifire Step 3: Configure Firebase Credentials Add your Firebase project ID to your .env file: FIREBASE_PROJECT_ID=your-project-id Place your Firebase service account credentials JSON file in your Laravel storage directory: # Move the downloaded JSON file to your project mv /path/to/your-firebase-credentials.json storage/firebase.json Important: Make sure to add storage/firebase.json to your .gitignore file to keep your credentials secure. Step 3: Publish Package Files Publish the package configuration and migration files: # Publish everything php artisan vendor:publish --provider="DevKandil\NotiFire\FcmServiceProvider" # Alternatively, publish specific components php artisan vendor:publish --tag=fcm-config # Configuration file php artisan vendor:publish --tag=fcm-migrations # Database migrations php artisan vendor:publish --tag=fcm-notifications # Example notification php artisan vendor:publish --tag=fcm-contracts # Interface contracts php artisan vendor:publish --tag=fcm-enums # Enums (MessagePriority) php artisan vendor:publish --tag=fcm-traits # Traits (HasFcm) Step 4: Customize Configuration (Optional) If you need to customize the package's behavior, you can modify the published configuration file at config/fcm.php. The most common configuration options include: credentials_path: The path to your Firebase service account JSON file project_id: Your Firebase project ID (defaults to using the value from your .env file) Step 5: Run Migrations Run the migrations to create the necessary database tables: php artisan migrate This will add the fcm_token field to your users table. Step 6: Update Your User Model Update your User model to make the fcm_token field fillable: // In App\Models\User.php protected $fillable = [ // existing fields... 'fcm_token', ]; Add the HasFcm trait to your User model: // In App\Models\User.php use DevKandil\NotiFire\Traits\HasFcm; class User extends Authenticatable { use HasFactory, Notifiable, HasFcm; // Your existing code... } Step 7: Set Up Token Updates (Optional) The package includes a built-in controller for updating FCM tokens. If you want to enable this functionality, ensure your API routes are properly set up with Sanctum authentication: Configure Sanctum for your application: For Laravel 11: Sanctum comes pre-installed in Laravel 11. Simply run the Sanctum installation command: php artisan install:api This command will: Configure Sanctum Set up the necessary API routes Create the required database migrations Set up the proper middleware configuration For Laravel 10 or earlier: Install and configure Sanctum manually: composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate Then add the Sanctum middleware to your api middleware group in app/Http/Kernel.php: 'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], Add the Sanctum trait to your User model (if you haven't already):

May 11, 2025 - 20:38
 0
Notifier: A Comprehensive Installation and Configuration Guide to integrate Firebase Cloud Messaging (FCM)

In today's mobile-first world, push notifications have become essential for engaging users with timely updates and information. For Laravel developers looking to integrate Firebase Cloud Messaging (FCM) into their applications, the Laravel FCM Notifier package by Abdelrazek Kandil offers an elegant solution that aligns perfectly with Laravel's design philosophy.

This comprehensive guide will walk you through setting up and configuring the Notifier package, providing practical examples for all available notification methods.

What is Notifier?

Notifier is a package that seamlessly integrates Firebase Cloud Messaging with Laravel's notification system. It provides a fluent interface for building notifications, supports both simple and complex FCM messages, automatically logs delivery status, and includes database migrations for storing FCM tokens.

Prerequisites

Before installing Notifier, ensure you have:

  1. A Laravel project (version 8.0 or higher recommended)
  2. Composer installed
  3. A Firebase project with FCM enabled
  4. A service account JSON file from Firebase

Step 1: Create a Firebase Project

If you don't already have a Firebase project, follow these steps:

  1. Go to the Firebase Console
  2. Click "Add project" and follow the setup wizard
  3. Once your project is created, navigate to Project Settings
  4. Click on the "Service accounts" tab
  5. Click "Generate new private key" to download your Firebase service account credentials JSON file
  6. Make note of your Firebase project ID, which you'll need later

Step 2: Install the Package

Open your terminal and navigate to your Laravel project directory. Install the package using Composer:

composer require devkandil/notifire

Step 3: Configure Firebase Credentials

  1. Add your Firebase project ID to your .env file:
FIREBASE_PROJECT_ID=your-project-id
  1. Place your Firebase service account credentials JSON file in your Laravel storage directory:
# Move the downloaded JSON file to your project
mv /path/to/your-firebase-credentials.json storage/firebase.json

Important: Make sure to add storage/firebase.json to your .gitignore file to keep your credentials secure.

Step 3: Publish Package Files

Publish the package configuration and migration files:

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

# Alternatively, publish specific components
php artisan vendor:publish --tag=fcm-config        # Configuration file
php artisan vendor:publish --tag=fcm-migrations    # Database migrations
php artisan vendor:publish --tag=fcm-notifications # Example notification
php artisan vendor:publish --tag=fcm-contracts     # Interface contracts
php artisan vendor:publish --tag=fcm-enums         # Enums (MessagePriority)
php artisan vendor:publish --tag=fcm-traits        # Traits (HasFcm)

Step 4: Customize Configuration (Optional)

If you need to customize the package's behavior, you can modify the published configuration file at config/fcm.php. The most common configuration options include:

  • credentials_path: The path to your Firebase service account JSON file
  • project_id: Your Firebase project ID (defaults to using the value from your .env file)

Step 5: Run Migrations

Run the migrations to create the necessary database tables:

php artisan migrate

This will add the fcm_token field to your users table.

Step 6: Update Your User Model

  1. Update your User model to make the fcm_token field fillable:
// In App\Models\User.php
protected $fillable = [
    // existing fields...
    'fcm_token',
];
  1. Add the HasFcm trait to your User model:
// In App\Models\User.php
use DevKandil\NotiFire\Traits\HasFcm;

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

    // Your existing code...
}

Step 7: Set Up Token Updates (Optional)

The package includes a built-in controller for updating FCM tokens. If you want to enable this functionality, ensure your API routes are properly set up with Sanctum authentication:

  1. Configure Sanctum for your application:

For Laravel 11:
Sanctum comes pre-installed in Laravel 11. Simply run the Sanctum installation command:

php artisan install:api

This command will:

  • Configure Sanctum
  • Set up the necessary API routes
  • Create the required database migrations
  • Set up the proper middleware configuration

For Laravel 10 or earlier:
Install and configure Sanctum manually:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Then add the Sanctum middleware to your api middleware group in app/Http/Kernel.php:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
  1. Add the Sanctum trait to your User model (if you haven't already):
use Laravel\Sanctum\HasApiTokens;

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

    // Your existing code...
}

Now, your frontend application can update the FCM token by making a POST request to /fcm/token with the following payload:

{
    "fcm_token": "user-fcm-token-here"
}

Step 8: Create a Custom Notification (Optional)

If you want to create a custom notification, you can use the Laravel artisan command to generate a new notification class:

php artisan make:notification PushNotification

Then, modify the generated notification class to include FCM channel support:



namespace App\Notifications;

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

class PushNotification extends Notification
{
    use Queueable;

    protected $title;
    protected $body;

    /**
     * Create a new notification instance.
     */
    public function __construct($title, $body)
    {
        $this->title = $title;
        $this->body = $body;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array
     */
    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)
            ->image('https://example.com/notification-image.jpg')
            ->sound('default')
            ->clickAction('OPEN_ACTIVITY')
            ->icon('notification_icon')
            ->color('#FF5733')
            ->priority(MessagePriority::HIGH)
            ->data([
                'notification_id' => uniqid('notification_'),
                'timestamp' => now()->toIso8601String(),
            ]);
    }
}

Using Laravel FCM Notifier

Now that everything is set up, let's explore the different ways to send notifications using Laravel FCM Notifier.

Method 1: Using the Facade

The Facade provides a fluent interface for sending notifications:

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

// Get the authenticated user
$user = auth()->user();

// Send notification
Fcm::withTitle('New Message')
    ->withBody('You have a new message from Sarah.')
    ->withImage('https://picsum.photos/seed/picsum/200/200')
    ->withSound('default')
    ->withPriority(MessagePriority::HIGH)
    ->withIcon('message_icon')
    ->withColor('#000000')
    ->sendNotification($user->fcm_token);

Method 2: Using Dependency Injection

You can also use dependency injection to get an instance of the FCM service:

use DevKandil\NotiFire\Contracts\FcmServiceInterface;
use DevKandil\NotiFire\Enums\MessagePriority;

// Get the authenticated user
$user = auth()->user();

// Get the FCM service instance
$fcm = app(FcmServiceInterface::class);

// Send notification
$fcm->withTitle('Order Shipped')
    ->withBody('Your order #1234 has been shipped and is on its way.')
    ->withImage('https://picsum.photos/seed/picsum/200/200')
    ->withIcon('shipping_truck')
    ->withColor('#FF5733')
    ->withSound('default')
    ->withPriority(MessagePriority::HIGH)
    ->withAdditionalData(['key' => 'value'])
    ->sendNotification($user->fcm_token);

Method 3: Using Laravel's Notification System

If you prefer to use Laravel's built-in notification system:

use App\Notifications\PushNotification;
// Or use the example notification provided by the package
use DevKandil\NotiFire\Notifications\ExampleNotification;

// Get the authenticated user
$user = auth()->user();

// Send notification
$user->notify(new ExampleNotification('