Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Firebase Notifier Laravel Package

symfony/firebase-notifier

Symfony Notifier bridge for Firebase Cloud Messaging. Configure via FIREBASE_DSN and send notifications with platform-specific options using AndroidNotification, IOSNotification, or WebNotification to customize icons, sounds, actions, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package (via Symfony Notifier bridge):

    composer require symfony/notifier firebase/php-jwt
    

    Note: Laravel lacks native Notifier support; use a custom bridge or Symfony’s Chatter directly.

  2. Configure Firebase DSN in .env:

    FIREBASE_DSN=firebase://PROJECT_ID:PRIVATE_KEY@default
    
  3. First Notification (Android Example):

    use Symfony\Component\Notifier\Message\ChatMessage;
    use Symfony\Component\Notifier\Bridge\Firebase\Notification\AndroidNotification;
    use Symfony\Component\Notifier\Chatter\ChatterInterface;
    
    // Instantiate Chatter (Laravel: bind to service container)
    $chatter = new ChatterInterface();
    
    $message = new ChatMessage('Hello from Laravel!');
    $message->options(
        (new AndroidNotification('/topics/news'))
            ->title('Laravel Alert')
            ->icon('ic_notification')
    );
    
    $chatter->send($message);
    
  4. Verify Setup:

    • Use Firebase Console’s DebugView to check received messages.

Implementation Patterns

1. Platform-Specific Notifications

Workflow:

  • Use AndroidNotification, IOSNotification, or WebNotification classes to target specific platforms.
  • Example: Send iOS notifications with custom actions:
    $iosOptions = (new IOSNotification())
        ->badge(5)
        ->sound('ping.aiff')
        ->mutableContent(true)
        ->category('MESSAGE_CATEGORY')
        ->addAction('reply', 'Reply', 'reply.php', 'default')
        ->addAction('archive', 'Archive', 'archive.php', 'archive');
    $message->options($iosOptions);
    

2. Topic-Based Subscriptions

Use Case: Broadcast to user segments (e.g., "premium_users").

  • Implementation:
    $message->options(
        (new AndroidNotification('/topics/premium_users'))
            ->priority('high')
    );
    
  • Laravel Integration: Pair with Eloquent events or Laravel Nova actions to dynamically assign topics.

3. Deep Linking

Pattern: Use clickAction (Android) or url (Web/iOS) for deep links.

  • Example:
    $androidOptions = (new AndroidNotification('/topics/news'))
        ->clickAction('OPEN_ACTIVITY_1')
        ->addData(['screen' => 'article', 'id' => 123]);
    

4. Conditional Payloads

Workflow: Dynamically set options based on user/device data.

  • Example:
    $options = $user->isIos()
        ? (new IOSNotification())->badge($user->unreadCount)
        : (new AndroidNotification())->priority('high');
    $message->options($options);
    

5. Integration with Laravel Queues

Pattern: Dispatch notifications via Laravel’s queue system.

  • Step 1: Create a notification class:
    namespace App\Notifications;
    
    use Illuminate\Bus\Queueable;
    use Symfony\Component\Notifier\Message\ChatMessage;
    use Symfony\Component\Notifier\Bridge\Firebase\Notification\AndroidNotification;
    
    class FirebaseAlert implements ShouldQueue
    {
        use Queueable;
    
        public function send($notifiable)
        {
            $message = new ChatMessage('Your alert!');
            $message->options(
                (new AndroidNotification('/topics/alerts'))
                    ->title('Urgent')
                    ->priority('high')
            );
    
            app('firebase.chatter')->send($message);
        }
    }
    
  • Step 2: Bind ChatterInterface to Laravel’s container in AppServiceProvider:
    $this->app->singleton('firebase.chatter', function () {
        return new \Symfony\Component\Notifier\Chatter\Chatter(
            new \Symfony\Component\Notifier\Transport\FirebaseTransport(
                $_ENV['FIREBASE_DSN']
            )
        );
    });
    

6. Testing

Pattern: Use Symfony’s TransportFactoryTestCase (deprecated in v7.2+) or mock the Chatter.

  • Example:
    public function testFirebaseNotification()
    {
        $chatter = $this->createMock(ChatterInterface::class);
        $chatter->expects($this->once())
                ->method('send')
                ->with($this->isInstanceOf(ChatMessage::class));
    
        $this->app->instance('firebase.chatter', $chatter);
    
        // Trigger notification logic...
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Ecosystem Mismatch:

    • Issue: Laravel’s Bus/Events systems don’t natively support Symfony’s ChatterInterface.
    • Fix: Create a Laravel-specific facade or use a trait to adapt Symfony’s Notifier:
      trait UsesFirebaseNotifier
      {
          protected function sendFirebaseNotification(ChatMessage $message)
          {
              app('firebase.chatter')->send($message);
          }
      }
      
  2. Firebase DSN Format:

    • Issue: The DSN firebase://USER:PASS@default is deprecated in favor of service account JSON keys.
    • Fix: Use the Firebase Admin SDK for modern auth:
      $transport = new FirebaseTransport(
          new \Symfony\Component\Notifier\Bridge\Firebase\Transport\FirebaseTransportOptions(
              'path/to/serviceAccount.json'
          )
      );
      
  3. PHP Version Requirements:

    • Issue: v8.0.0+ requires PHP ≥8.4, which may conflict with Laravel 9.x.
    • Fix: Downgrade to v7.4.* or upgrade Laravel:
      composer require symfony/firebase-notifier:^7.4
      
  4. Payload Size Limits:

    • Issue: Firebase FCM limits payloads to 4KB. Complex notifications may fail.
    • Fix: Use data payloads for large content and notification payloads for alerts:
      $message->options(
          (new AndroidNotification())
              ->setData(['large_data' => json_encode($data)])
              ->title('Short alert')
      );
      
  5. Topic Subscription Management:

    • Issue: Topics must be pre-registered in Firebase Console or via the Admin SDK.
    • Fix: Use the Firebase Admin SDK to manage topics programmatically:
      $admin = app('firebase.admin');
      $admin->messaging()->subscribeToTopic('user123', '/topics/news');
      
  6. Web Push Limitations:

    • Issue: Web notifications require a VAPID key (not supported by this package).
    • Fix: Use a dedicated web push service (e.g., Web-Push-PHP).

Debugging Tips

  1. Enable Firebase Debugging:

    • Set FIREBASE_DEBUG=true in .env to log raw FCM responses.
  2. Validate Payloads:

  3. Check Quotas:

    • Monitor Firebase Console’s Quotas page for rate limits.
  4. Laravel Logs:

    • Wrap Chatter::send() in a try-catch to log failures:
      try {
          $chatter->send($message);
      } catch (\Throwable $e) {
          \Log::error('Firebase notification failed', ['error' => $e->getMessage()]);
      }
      

Extension Points

  1. Custom Notification Classes:

    • Extend AndroidNotification, IOSNotification, or WebNotification to add platform-specific logic:
      class CustomAndroidNotification extends AndroidNotification
      {
          public function setCustomKeyValue(string $key, $value): self
          {
              $this->data[$key] = $value;
              return $this;
          }
      }
      
  2. Transport Decorators:

    • Decorate FirebaseTransport to add retries or analytics:
      class AnalyticsFirebaseTransport implements TransportInterface
      {
          private $decorated;
      
          public function __construct(FirebaseTransport $transport)
          {
              $this->decorated = $transport;
          }
      
          public function send(ChatMessage $message): void
          {
              // Log analytics before sending
              \Log::info('Sending Firebase notification', ['topic' => $message->options()->getTopic()]);
      
              $this->decorated->send($message
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky