PHPackages                             humamkerdiah/fcm-notifications - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. humamkerdiah/fcm-notifications

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

humamkerdiah/fcm-notifications
==============================

A Laravel package for sending Firebase Cloud Messaging (FCM) push notifications with support for both legacy API and FCM HTTP v1 API. Features OAuth 2.0 authentication, batch processing, and comprehensive error handling.

2.0.1(1y ago)012MITPHPPHP ^7.4|^8.0

Since Apr 20Pushed 1y ago1 watchersCompare

[ Source](https://github.com/humam-k98/fcm-notifications)[ Packagist](https://packagist.org/packages/humamkerdiah/fcm-notifications)[ RSS](/packages/humamkerdiah-fcm-notifications/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (9)Versions (4)Used By (0)

Laravel FCM Notifications
=========================

[](#laravel-fcm-notifications)

A Laravel package for sending Firebase Cloud Messaging (FCM) notifications with support for both legacy API and the new FCM HTTP v1 API.

About
-----

[](#about)

Laravel FCM Notifications is a powerful package for integrating Firebase Cloud Messaging (FCM) into your Laravel application. It supports both the legacy FCM API and the new FCM HTTP v1 API (recommended). Send push notifications to individual users or groups, manage topics, and more with simple configuration and seamless integration.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [FCM HTTP v1 API (Recommended)](#fcm-http-v1-api-recommended)
- [Legacy API Support](#legacy-api-support)
- [Usage](#usage)
- [Migration Guide](#migration-guide)
- [License](#license)

Features
--------

[](#features)

- ✅ **FCM HTTP v1 API Support** - OAuth 2.0 authentication with service account keys
- ✅ **Legacy API Support** - Backwards compatibility with server key authentication
- ✅ Easy integration with Laravel notifications
- ✅ Send notifications to single or multiple users
- ✅ Topic-based messaging for targeted notifications
- ✅ Batch processing for multiple device tokens
- ✅ Comprehensive error handling and retry mechanisms
- ✅ Support for both mobile and web push notifications
- ✅ Laravel 8, 9, 10, and 11 compatibility

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require humamkerdiah/fcm-notifications
```

Configuration
-------------

[](#configuration)

After installation, publish the config file:

```
php artisan vendor:publish --tag=fcm-config
```

This will create a `config/fcm.php` file where you can configure your FCM settings.

FCM HTTP v1 API (Recommended)
-----------------------------

[](#fcm-http-v1-api-recommended)

The v1 API uses OAuth 2.0 authentication and is Google's recommended approach for FCM.

### Setup for v1 API

[](#setup-for-v1-api)

1. **Get Service Account Key:**

    - Go to [Firebase Console](https://console.firebase.google.com/)
    - Select your project → Project Settings → Service Accounts
    - Click "Generate new private key" and download the JSON file
2. **Update your `.env` file:**

```
FCM_API_VERSION=v1
FCM_PROJECT_ID=your-firebase-project-id
FCM_SERVICE_ACCOUNT_KEY_PATH=/path/to/your/service-account-key.json
```

Alternatively, you can use the `GOOGLE_APPLICATION_CREDENTIALS` environment variable:

```
GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json
FCM_API_VERSION=v1
FCM_PROJECT_ID=your-firebase-project-id
```

Legacy API Support
------------------

[](#legacy-api-support)

The package still supports the legacy server key authentication for backwards compatibility.

### Setup for Legacy API

[](#setup-for-legacy-api)

Update your `.env` file:

```
FCM_API_VERSION=legacy
FCM_SERVER_KEY=your-server-key-here
```

Usage
-----

[](#usage)

### Using Laravel Notifications

[](#using-laravel-notifications)

There are two ways to use FCM notifications in your Laravel application:

#### 1. Using the FCM Channel Class

[](#1-using-the-fcm-channel-class)

```
use Humamkerdiah\FcmNotifications\Channels\FcmChannel;

class NewMessage extends Notification
{
    public function via($notifiable)
    {
        return [FcmChannel::class];
    }

    public function toFcm($notifiable)
    {
        return (new FcmMessage())
            ->setTitle('New Message')
            ->setBody('You have a new message!')
            ->setData([
                'message_id' => '123',
                'url' => '/messages/123'
            ]);
    }
}
```

#### 2. Using the Channel Name

[](#2-using-the-channel-name)

```
class NewMessage extends Notification
{
    public function via($notifiable)
    {
        return ['fcm'];  // Use the registered channel name
    }

    public function toFcm($notifiable)
    {
        return (new FcmMessage())
            // ... same as above
    }
}
```

### Setting Up Your Model

[](#setting-up-your-model)

Make your model use FCM notifications by implementing the `routeNotificationForFcm` method:

```
use Illuminate\Notifications\Notifiable;

class User extends Model
{
    use Notifiable;

    public function routeNotificationForFcm($notification)
    {
        return $this->device_token; // Return a single token
        // Or return multiple tokens:
        // return $this->device_tokens->pluck('token')->toArray();
    }
}
```

### Sending Notifications

[](#sending-notifications)

```
// To a single user
$user->notify(new NewMessage());

// To multiple users
Notification::send($users, new NewMessage());

// Using the facade for direct FCM operations
use Humamkerdiah\FcmNotifications\Facades\FcmNotification;

// Send to specific devices
$message = new FcmMessage();
$message->setTitle('Hello')
       ->setBody('This is a test notification')
       ->setData(['key' => 'value'])
       ->setTokens(['device-token-1', 'device-token-2']);

FcmNotification::sendToDevices($message);

// Or send to a topic
$message->setTopic('news');
FcmNotification::sendToTopic($message);
```

### Topic Management

[](#topic-management)

```
// Subscribe tokens to a topic
FcmNotification::subscribeToTopic('news', ['device-token-1', 'device-token-2']);

// Unsubscribe tokens from a topic
FcmNotification::unsubscribeFromTopic('news', ['device-token-1', 'device-token-2']);
```

Error Handling
--------------

[](#error-handling)

The package provides comprehensive error handling for both API versions:

### v1 API Response Format

[](#v1-api-response-format)

```
try {
    $result = FcmNotification::sendToDevices($message);

    echo "Success count: " . $result['success_count'];
    echo "Failure count: " . $result['failure_count'];

    // Handle successful sends
    foreach ($result['results'] as $result) {
        echo "Token: " . $result['token'] . " - Message ID: " . $result['message_id'];
    }

    // Handle failures
    foreach ($result['errors'] as $error) {
        echo "Failed token: " . $error['token'] . " - Error: " . $error['error'];
    }

} catch (\Humamkerdiah\FcmNotifications\Exceptions\FcmNotificationException $e) {
    Log::error('FCM Notification failed: ' . $e->getMessage());
}
```

### Legacy API Response Format

[](#legacy-api-response-format)

```
try {
    $result = FcmNotification::sendToDevices($message);

    echo "Success: " . $result['success'];
    echo "Failure: " . $result['failure'];
    echo "Canonical IDs: " . $result['canonical_ids'];

} catch (\Exception $e) {
    Log::error('FCM Notification failed: ' . $e->getMessage());
}
```

Migration Guide
---------------

[](#migration-guide)

If you're upgrading from the legacy API to v1 API, see our [Migration Guide](MIGRATION_GUIDE.md) for detailed instructions.

Testing
-------

[](#testing)

When testing your application, you can mock the FCM notifications:

```
use Mockery;
use Humamkerdiah\FcmNotifications\Contracts\FcmNotificationSender;

public function test_it_sends_fcm_notification()
{
    $mock = Mockery::mock(FcmNotificationSender::class);

    // For v1 API
    $mock->shouldReceive('sendToDevices')->once()->andReturn([
        'success_count' => 1,
        'failure_count' => 0,
        'results' => [['token' => 'test-token', 'success' => true, 'message_id' => 'test-message-id']],
        'errors' => []
    ]);

    $this->app->instance(FcmNotificationSender::class, $mock);

    // Your test code here
}
```

Requirements
------------

[](#requirements)

- PHP 7.4 or higher
- Laravel 8.0 or higher
- GuzzleHTTP 7.0 or higher
- Google Auth Library (for v1 API)

Security Considerations
-----------------------

[](#security-considerations)

- Store service account keys securely and never commit them to version control
- Use environment variables for all sensitive configuration
- Consider using Google Cloud Secret Manager in production
- Regularly rotate your service account keys

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance46

Moderate activity, may be stable

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 77.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Total

3

Last Release

406d ago

Major Versions

v1.0.0 → 2.0.02025-05-25

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/174418125?v=4)[Humam Kerdiah](/maintainers/humam-k98)[@humam-k98](https://github.com/humam-k98)

---

Top Contributors

[![humam-k98](https://avatars.githubusercontent.com/u/174418125?v=4)](https://github.com/humam-k98 "humam-k98 (7 commits)")[![humamkerdiah](https://avatars.githubusercontent.com/u/39071114?v=4)](https://github.com/humamkerdiah "humamkerdiah (2 commits)")

---

Tags

laravelpushnotificationsfirebaseFCMoauth 2.0push notificationsbatch processingservice accountfirebase notificationsFCM Laravelsend pushlaravel pushFCM integrationFCM v1 API

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/humamkerdiah-fcm-notifications/health.svg)

```
[![Health](https://phpackages.com/badges/humamkerdiah-fcm-notifications/health.svg)](https://phpackages.com/packages/humamkerdiah-fcm-notifications)
```

###  Alternatives

[laravel/socialite

Laravel wrapper around OAuth 1 &amp; OAuth 2 libraries.

5.7k108.5M889](/packages/laravel-socialite)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M167](/packages/spatie-laravel-health)[kreait/laravel-firebase

A Laravel package for the Firebase PHP Admin SDK

1.3k18.7M49](/packages/kreait-laravel-firebase)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M7](/packages/propaganistas-laravel-disposable-email)[fleetbase/core-api

Core Framework and Resources for Fleetbase API

1235.9k20](/packages/fleetbase-core-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
