PHPackages                             nfon-andrew/laravel-firebase-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. nfon-andrew/laravel-firebase-notifications

ActiveLibrary

nfon-andrew/laravel-firebase-notifications
==========================================

A Laravel package for sending Firebase Cloud Messaging (FCM) push notifications and email notifications

14PHP

Since Oct 25Pushed 6mo agoCompare

[ Source](https://github.com/andrew21-mch/laravel-firebase-notifications)[ Packagist](https://packagist.org/packages/nfon-andrew/laravel-firebase-notifications)[ RSS](/packages/nfon-andrew-laravel-firebase-notifications/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Firebase Notifications
==============================

[](#laravel-firebase-notifications)

A comprehensive Laravel package for sending push notifications via Firebase Cloud Messaging (FCM) and email notifications with advanced device token management, notification logging, and analytics.

Features
--------

[](#features)

- 🔥 Firebase Cloud Messaging (FCM) push notifications
- ✉️ Email notifications with customizable templates
- 📱 Multi-platform support (iOS, Android, Web)
- 📊 Notification logging and analytics
- 🎯 Device token management
- ⚡ Queue support for better performance
- 👥 Send to individual users, multiple users, or all users
- 📈 Notification statistics and reporting
- 🔒 Graceful error handling and logging

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

[](#installation)

### 1. Install the package

[](#1-install-the-package)

```
composer require nfon-andrew/laravel-firebase-notifications
```

### 2. Publish the package files

[](#2-publish-the-package-files)

```
# Publish configuration, migrations, and views
php artisan vendor:publish --provider="NfonAndrew\LaravelFirebaseNotifications\LaravelFirebaseNotificationsServiceProvider"

# Or publish specific assets
php artisan vendor:publish --provider="NfonAndrew\LaravelFirebaseNotifications\LaravelFirebaseNotificationsServiceProvider" --tag="config"
php artisan vendor:publish --provider="NfonAndrew\LaravelFirebaseNotifications\LaravelFirebaseNotificationsServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="NfonAndrew\LaravelFirebaseNotifications\LaravelFirebaseNotificationsServiceProvider" --tag="views"
```

### 3. Run migrations

[](#3-run-migrations)

```
php artisan migrate
```

### 4. Configure Firebase

[](#4-configure-firebase)

1. Create a Firebase project in the [Firebase Console](https://console.firebase.google.com/)
2. Generate a service account key:

    - Go to Project Settings &gt; Service Accounts
    - Click "Generate new private key"
    - Save the JSON file securely
3. Add Firebase configuration to your `.env` file:

```
FIREBASE_PROJECT_ID=your-firebase-project-id
FIREBASE_CREDENTIALS_PATH=path/to/your/firebase-credentials.json

# Optional FCM settings
FCM_SERVER_KEY=your-fcm-server-key
FCM_SENDER_ID=your-sender-id
```

### 5. Configure Email (Optional)

[](#5-configure-email-optional)

```
MAIL_MAILER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=587
MAIL_USERNAME=your-email@example.com
MAIL_PASSWORD=your-email-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@yourapp.com
MAIL_FROM_NAME="${APP_NAME}"
```

Console Commands
----------------

[](#console-commands)

The package includes several Artisan commands to help you manage Firebase notifications:

### Installation Command

[](#installation-command)

```
# Install and configure the package
php artisan firebase:install
```

This command will:

- Publish configuration files
- Publish and run migrations
- Publish views
- Create example environment variables
- Generate example controller
- Show next steps

### Testing Commands

[](#testing-commands)

```
# Test Firebase connection and send a test notification
php artisan firebase:test

# Test with a specific token
php artisan firebase:test --token=your-device-token

# Test with a specific user's tokens
php artisan firebase:test --user=1

# Test with custom message
php artisan firebase:test --title="Test" --body="Custom test message"
```

### Sending Notifications

[](#sending-notifications)

```
# Send notification to a specific user
php artisan firebase:send --user=1 --title="Hello" --body="Message"

# Send to multiple users
php artisan firebase:send --users=1,2,3 --title="Bulk" --body="Message"

# Send to all users
php artisan firebase:send --all --title="Broadcast" --body="Everyone gets this"

# Send with additional data
php artisan firebase:send --user=1 --title="Alert" --body="Message" --data='{"key":"value"}'

# Enable email notifications too
php artisan firebase:send --user=1 --title="Alert" --body="Message" --push --email
```

### Cleanup Commands

[](#cleanup-commands)

```
# Clean up old device tokens and notification logs
php artisan firebase:cleanup --tokens --logs

# Clean up only tokens (inactive for 90+ days)
php artisan firebase:cleanup --tokens --inactive-days=90

# Clean up only logs (older than 30 days)
php artisan firebase:cleanup --logs --days=30

# Preview what would be deleted (dry run)
php artisan firebase:cleanup --tokens --logs --dry-run

# Skip confirmation prompts
php artisan firebase:cleanup --tokens --logs --force
```

### Statistics and Analytics

[](#statistics-and-analytics)

```
# Show notification statistics
php artisan firebase:stats

# Show detailed statistics
php artisan firebase:stats --detailed

# Analyze specific time period
php artisan firebase:stats --days=7

# Export statistics to CSV
php artisan firebase:stats --export=stats.csv
```

### List All Commands

[](#list-all-commands)

```
# Show all available Firebase commands
php artisan firebase:list
```

### Command Help

[](#command-help)

```
# Get help for any specific command
php artisan firebase:test --help
php artisan firebase:send --help
php artisan firebase:cleanup --help
```

Usage
-----

[](#usage)

### Basic Notification Sending

[](#basic-notification-sending)

```
use NfonAndrew\LaravelFirebaseNotifications\Services\NotificationService;

class YourController extends Controller
{
    public function __construct(
        private NotificationService $notificationService
    ) {}

    public function sendNotification()
    {
        // Send to a specific user (push notification)
        $result = $this->notificationService->sendToUser(
            userId: 1,
            title: 'Hello!',
            body: 'This is a test notification',
            data: ['key' => 'value'],
            options: ['push' => true]
        );

        // Send to multiple users
        $result = $this->notificationService->sendToUsers(
            userIds: [1, 2, 3],
            title: 'Bulk Notification',
            body: 'This goes to multiple users'
        );

        // Send to all users
        $result = $this->notificationService->sendToAllUsers(
            title: 'Global Announcement',
            body: 'This goes to everyone!'
        );
    }
}
```

### Using Laravel's Notification System

[](#using-laravels-notification-system)

```
use NfonAndrew\LaravelFirebaseNotifications\Notifications\FirebaseNotification;

// Send via Laravel's notification system
$user->notify(new FirebaseNotification(
    title: 'Order Update',
    body: 'Your order has been shipped!',
    data: ['order_id' => 123],
    options: [
        'android' => [
            'priority' => 'high',
            'notification' => [
                'sound' => 'default'
            ]
        ]
    ]
));
```

### Device Token Management

[](#device-token-management)

```
// Register a device token
$this->notificationService->registerDeviceToken(
    userId: 1,
    token: 'fcm-device-token',
    platform: 'android', // ios, android, web
    deviceId: 'unique-device-id'
);

// Unregister a device token
$this->notificationService->unregisterDeviceToken('fcm-device-token');

// Get user's device tokens
$tokens = $this->notificationService->getUserDeviceTokens(1);

// Clean up inactive tokens (older than 30 days)
$cleaned = $this->notificationService->cleanupInactiveTokens(30);
```

### Email Notifications

[](#email-notifications)

```
// Send email + push notification
$result = $this->notificationService->sendToUser(
    userId: 1,
    title: 'Important Update',
    body: 'Please check your account',
    options: [
        'push' => true,
        'email' => true,
        'email_address' => 'user@example.com',
        'email_template' => 'emails.custom-template'
    ]
);
```

### Advanced Platform Options

[](#advanced-platform-options)

```
$options = [
    'android' => [
        'priority' => 'high',
        'notification' => [
            'sound' => 'default',
            'color' => '#FF0000',
            'icon' => 'ic_notification'
        ],
        'data' => [
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK'
        ]
    ],
    'apns' => [
        'payload' => [
            'aps' => [
                'sound' => 'default',
                'badge' => 1,
                'alert' => [
                    'title' => 'Custom Title',
                    'body' => 'Custom Body'
                ]
            ]
        ]
    ],
    'webpush' => [
        'notification' => [
            'icon' => 'https://example.com/icon.png',
            'click_action' => 'https://example.com'
        ]
    ]
];

$this->notificationService->sendToUser(1, 'Title', 'Body', [], $options);
```

API Endpoints
-------------

[](#api-endpoints)

You can create API endpoints to manage notifications:

```
// routes/api.php
Route::post('/notifications/send', [NotificationController::class, 'send']);
Route::post('/notifications/send-to-users', [NotificationController::class, 'sendToUsers']);
Route::post('/notifications/send-to-all', [NotificationController::class, 'sendToAll']);
Route::post('/device-tokens/register', [DeviceTokenController::class, 'register']);
Route::delete('/device-tokens/{token}', [DeviceTokenController::class, 'unregister']);
Route::get('/notifications/stats', [NotificationController::class, 'getStats']);
```

Statistics and Analytics
------------------------

[](#statistics-and-analytics-1)

```
// Get notification statistics for the last 30 days
$stats = $this->notificationService->getStatistics(30);
/*
Returns:
[
    'total_notifications' => 150,
    'sent' => 145,
    'failed' => 3,
    'partial' => 2,
    'push_notifications' => 120,
    'email_notifications' => 30,
    'success_rate' => 96.67
]
*/

// Get notification logs
$logs = $this->notificationService->getNotificationLogs(50, 0);
```

Database Schema
---------------

[](#database-schema)

### Device Tokens Table

[](#device-tokens-table)

```
CREATE TABLE device_tokens (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    token VARCHAR(255) UNIQUE NOT NULL,
    platform ENUM('ios', 'android', 'web') DEFAULT 'android',
    device_id VARCHAR(255) NULL,
    is_active BOOLEAN DEFAULT TRUE,
    last_used_at TIMESTAMP NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_user_active (user_id, is_active),
    INDEX idx_platform (platform),
    INDEX idx_last_used (last_used_at)
);
```

### Notification Logs Table

[](#notification-logs-table)

```
CREATE TABLE notification_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NULL,
    type VARCHAR(50) DEFAULT 'firebase',
    channel VARCHAR(50) DEFAULT 'push',
    title VARCHAR(255) NOT NULL,
    body TEXT NOT NULL,
    data JSON NULL,
    recipients JSON NOT NULL,
    status ENUM('sent', 'failed', 'partial') DEFAULT 'sent',
    response_data JSON NULL,
    sent_at TIMESTAMP NOT NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_user_sent (user_id, sent_at),
    INDEX idx_type_channel (type, channel),
    INDEX idx_status (status),
    INDEX idx_sent_at (sent_at)
);
```

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

[](#configuration)

The package configuration is published to `config/firebase-notifications.php`:

```
return [
    'credentials' => env('FIREBASE_CREDENTIALS_PATH'),
    'project_id' => env('FIREBASE_PROJECT_ID'),

    'fcm' => [
        'server_key' => env('FCM_SERVER_KEY'),
        'sender_id' => env('FCM_SENDER_ID'),
    ],

    'defaults' => [
        'android' => [
            'priority' => 'high',
            'notification' => [
                'sound' => 'default',
            ],
        ],
        'apns' => [
            'payload' => [
                'aps' => [
                    'sound' => 'default',
                ],
            ],
        ],
        'webpush' => [
            'notification' => [
                'requireInteraction' => true,
            ],
        ],
    ],

    'email' => [
        'default_template' => 'firebase-notifications::email-notification',
        'from_address' => env('MAIL_FROM_ADDRESS', 'noreply@example.com'),
        'from_name' => env('MAIL_FROM_NAME', 'App Notifications'),
    ],

    'database' => [
        'device_tokens_table' => 'device_tokens',
        'notification_logs_table' => 'notification_logs',
    ],
];
```

Testing
-------

[](#testing)

```
# Run package tests
./vendor/bin/phpunit packages/laravel-firebase-notifications/tests/

# Test notification sending manually
php artisan tinker
>>> app(NfonAndrew\LaravelFirebaseNotifications\Services\NotificationService::class)->sendToUser(1, 'Test', 'Message');
```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **Firebase credentials not found**

    - Ensure the credentials file path is correct
    - Check file permissions
    - Verify the JSON structure
2. **Device token not registered**

    - Make sure to register device tokens before sending notifications
    - Check if tokens are active
3. **Email sending fails**

    - Verify SMTP configuration
    - Check email template exists
    - Ensure queue workers are running if using queues
4. **Notifications not received**

    - Check Firebase project configuration
    - Verify device tokens are valid
    - Review notification logs for errors

### Logging

[](#logging)

The package logs errors and warnings to Laravel's default log channel. Check `storage/logs/laravel.log` for debugging information.

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

[](#security-considerations)

- 🔐 Keep your Firebase service account key secure
- 🔒 Validate user permissions before sending notifications
- 🚦 Implement rate limiting for notification endpoints
- 🧹 Sanitize notification content to prevent XSS
- 🔗 Use HTTPS for all endpoints

Performance Tips
----------------

[](#performance-tips)

- 📊 Use queues for bulk notifications
- 🧹 Regularly clean up inactive device tokens
- 📦 Batch notifications when sending to many users
- 📈 Monitor notification delivery rates
- 🗃️ Use database indexing for better query performance

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Support
-------

[](#support)

If you discover any security vulnerabilities or bugs, please send an email to .

For questions and support, please open an issue on GitHub.

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance46

Moderate activity, may be stable

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1f0394f5015ad66b7f1f420a27ad9f07ec33859a88531bf64b327cea988a7a56?d=identicon)[andrew21-mch](/maintainers/andrew21-mch)

---

Top Contributors

[![andrew21-mch](https://avatars.githubusercontent.com/u/58951422?v=4)](https://github.com/andrew21-mch "andrew21-mch (6 commits)")

### Embed Badge

![Health badge](/badges/nfon-andrew-laravel-firebase-notifications/health.svg)

```
[![Health](https://phpackages.com/badges/nfon-andrew-laravel-firebase-notifications/health.svg)](https://phpackages.com/packages/nfon-andrew-laravel-firebase-notifications)
```

PHPackages © 2026

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