nfon-andrew/laravel-firebase-notifications

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

Installs: 4

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/nfon-andrew/laravel-firebase-notifications

dev-main 2025-10-25 11:53 UTC

This package is auto-updated.

Last update: 2025-11-25 12:09:43 UTC


README

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

  • ๐Ÿ”ฅ 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

1. Install the package

composer require nfon-andrew/laravel-firebase-notifications

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

php artisan migrate

4. Configure Firebase

  1. Create a Firebase project in the Firebase Console

  2. Generate a service account key:

    • Go to Project Settings > 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)

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

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

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

# 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

# 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

# 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

# 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

# Show all available Firebase commands
php artisan firebase:list

Command Help

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

Usage

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

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

// 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

// 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

$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

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

// 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

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

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

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

# 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

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

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

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

  • ๐Ÿ“Š 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

  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

This package is open-sourced software licensed under the MIT license.

Support

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

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