PHPackages                             melsaka/laravel-firebase-messaging - 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. melsaka/laravel-firebase-messaging

ActiveLibrary

melsaka/laravel-firebase-messaging
==================================

Laravel package for Firebase Cloud Messaging

v1.0.0(8mo ago)00MITPHPPHP ^8.2

Since Aug 18Pushed 8mo agoCompare

[ Source](https://github.com/melsaka/laravel-firebase-messaging)[ Packagist](https://packagist.org/packages/melsaka/laravel-firebase-messaging)[ RSS](/packages/melsaka-laravel-firebase-messaging/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Laravel Firebase Messaging
==========================

[](#laravel-firebase-messaging)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4203753a49789e68d683a34a08c59e53cfde021ce8d7451466130db41e747927/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d656c73616b612f6c61726176656c2d66697265626173652d6d6573736167696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/melsaka/laravel-firebase-messaging)[![Total Downloads](https://camo.githubusercontent.com/dce56af899abb5c3bba98ecf35efc05d331264f1a31e5deac6d34d1adbd507fe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d656c73616b612f6c61726176656c2d66697265626173652d6d6573736167696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/melsaka/laravel-firebase-messaging)[![License](https://camo.githubusercontent.com/5dcc908d89af80e87e34caed3b12fc527d15d1a03905c9bc0cda11f258bf875d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d656c73616b612f6c61726176656c2d66697265626173652d6d6573736167696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/melsaka/laravel-firebase-messaging)

A Laravel package for sending Firebase Cloud Messages (FCM) with support for web push notifications, Android, and iOS platforms. This package provides a clean, fluent API for sending notifications to single or multiple devices with automatic token cleanup and error handling.

Features
--------

[](#features)

- 🚀 **Easy Integration** - Simple setup with Laravel auto-discovery
- 📱 **Multi-Platform Support** - Web, Android, and iOS notifications
- 🔄 **Automatic Token Cleanup** - Invalid tokens are automatically removed
- 🎯 **Flexible Targeting** - Send to single tokens or multiple devices
- 🛠️ **Configurable** - Customizable settings for all platforms
- 🧪 **Testable** - Built with testing in mind
- 📊 **Error Handling** - Comprehensive error handling and reporting

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

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.0 or higher
- Firebase project with FCM enabled

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

[](#installation)

You can install the package via Composer:

```
composer require melsaka/laravel-firebase-messaging
```

### Publish Configuration

[](#publish-configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=firebase-messaging

php artisan migrate
```

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

[](#configuration)

### Environment Variables

[](#environment-variables)

Add the following environment variables to your `.env` file:

```
FIREBASE_CREDENTIALS=/path/to/your/firebase-service-account.json
FIREBASE_PROJECT_ID=your-firebase-project-id
```

The path must be in the storage folder, for ex: `firebase/firebase-service-account.json`

### Firebase Setup

[](#firebase-setup)

1. Go to the [Firebase Console](https://console.firebase.google.com/)
2. Create a new project or select an existing one
3. Go to Project Settings → Service Accounts
4. Click "Generate new private key" to download your service account JSON file
5. Store the JSON file in your Laravel storage directory
6. Update the `FIREBASE_CREDENTIALS` path in your `.env` file

### Configuration File

[](#configuration-file)

The package configuration can be customized in `config/firebase-messaging.php`:

```
return [
    'credentials' => env('FIREBASE_CREDENTIALS', storage_path('app/firebase-credentials.json')),
    'project_id' => env('FIREBASE_PROJECT_ID'),
    'tokens_table' => 'fcm_tokens',
    'defaults' => [
        'android' => [
            'ttl' => '3600s',
            'priority' => 'normal',
            'color' => '#f45342',
            'sound' => 'default',
        ],
        'apns' => [
            'priority' => '10',
            'badge' => 42,
            'sound' => 'default',
        ],
    ],
];
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use Melsaka\LaravelFirebaseMessaging\Facades\FirebaseMessaging;

// Build a notification
$notification = FirebaseMessaging::buildNotificationMessage(
    title: 'Hello World',
    body: 'This is a test notification.',
    attributes: [
        'link' => 'https://your-app.com/page',
        'image' => 'https://your-app.com/image.png',
        'data' => [
            'custom_key' => 'custom_value',
        ]
    ]
);

// Send to a single token
$success = FirebaseMessaging::notify($notification, $fcmToken);

// Send to multiple tokens
$tokens = collect($fcmTokens); // Collection of FCM token objects
$success = FirebaseMessaging::notify($notification, $tokens);
```

### Advanced Usage

[](#advanced-usage)

#### Send to Specific Token

[](#send-to-specific-token)

```
$notification = [
    'title' => 'Order Update',
    'body' => 'Your order #12345 has been shipped!',
    'link' => 'https://your-app.com/orders/12345',
    'image' => 'https://your-app.com/images/order-shipped.png',
    'data' => [
        'order_id' => '12345',
        'status' => 'shipped'
    ]
];

$success = FirebaseMessaging::notifyToken($notification, $fcmToken);
```

#### Send to Multiple Devices

[](#send-to-multiple-devices)

```
use App\Models\User;

// Get all FCM tokens for a user
$user = User::find(1);
$tokens = $user->fcmTokens; // Assuming you have this relationship

$notification = FirebaseMessaging::buildNotificationMessage(
    title: 'Welcome Back!',
    body: 'We have new features waiting for you.',
    attributes: [
        'link' => 'https://your-app.com/dashboard',
        'image' => 'https://your-app.com/image.png',
        'data' => [
            'order_id' => '12345',
            'status' => 'shipped'
        ]
    ]
);

$success = FirebaseMessaging::notifyAll($notification, $tokens);
```

#### Using Dependency Injection

[](#using-dependency-injection)

```
use Melsaka\LaravelFirebaseMessaging\Services\FirebaseMessagingService;

class NotificationController extends Controller
{
    public function __construct(
        private FirebaseMessagingService $firebaseMessaging
    ) {}

    public function sendWelcomeNotification(User $user)
    {
        $notification = $this->firebaseMessaging->buildNotificationMessage(
            title: 'Welcome to Our App!',
            body: 'Thanks for joining us. Get started by exploring our features.',
            attributes: [
                'link' => 'https://your-app.com/dashboard',
                'image' => 'https://your-app.com/image.png',
                'data' => [
                    'order_id' => '12345',
                    'status' => 'shipped'
                ]
            ]
        );

        $tokens = $user->fcmTokens;

        return $this->firebaseMessaging->notify($notification, $tokens);
    }
}
```

Database Structure
------------------

[](#database-structure)

The package creates an `fcm_tokens` table with the following structure:

```
Schema::create('fcm_tokens', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('fcm_token')->unique();
    $table->string('device_type')->nullable();
    $table->string('device_id')->nullable();
    $table->timestamps();

    $table->index(['user_id', 'fcm_token']);
});
```

Model Relationships
-------------------

[](#model-relationships)

Add FCM token relationships to your User model:

```
use Illuminate\Database\Eloquent\Relations\HasMany;

class User extends Authenticatable
{
    public function fcmTokens(): HasMany
    {
        return $this->hasMany(FcmToken::class);
    }
}
```

Create an FCM Token model:

```
