PHPackages                             sendfirebase/notificationphp - 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. sendfirebase/notificationphp

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

sendfirebase/notificationphp
============================

A package for sending Firebase notifications in Laravel.

v1.0.6(8mo ago)10211MITPHPPHP ^7.4|^8.0|^8.1|^8.2|^8.3|^8.4

Since Jan 29Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/YacoubAl-hardari/firebasenotificationphp)[ Packagist](https://packagist.org/packages/sendfirebase/notificationphp)[ RSS](/packages/sendfirebase-notificationphp/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (8)Used By (0)

Firebase Notification Integration Package Documentation
=======================================================

[](#firebase-notification-integration-package-documentation)

A comprehensive solution for sending Firebase Cloud Messaging (FCM) notifications from a Laravel backend to Flutter applications.

[![Firebase-Laravel-Flutter](https://camo.githubusercontent.com/473e758749693918ece06663c699236811c301ca01d1c7c770779eca6c368cec/68747470733a2f2f73746f726167652e676f6f676c65617069732e636f6d2f6173736574732e69616e6b756d752e636f6d2f323032322f30332f4c61726176656c2d46697265626173652e77656270)](https://camo.githubusercontent.com/473e758749693918ece06663c699236811c301ca01d1c7c770779eca6c368cec/68747470733a2f2f73746f726167652e676f6f676c65617069732e636f6d2f6173736574732e69616e6b756d752e636f6d2f323032322f30332f4c61726176656c2d46697265626173652e77656270)

---

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

[](#table-of-contents)

- [Laravel Integration](#laravel-integration)
    - [Prerequisites](#laravel-prerequisites)
    - [Installation](#laravel-installation)
    - [Configuration](#laravel-configuration)
    - [Usage Examples](#laravel-usage-examples)
    - [Troubleshooting](#laravel-troubleshooting)
- [Flutter Integration](#flutter-integration)
    - [Prerequisites](#flutter-prerequisites)
    - [Setup &amp; Dependencies](#flutter-setup--dependencies)
    - [Notification Initialization and Handling](#flutter-notification-initialization-and-handling)
    - [Usage Examples](#flutter-usage-examples)
    - [Troubleshooting](#flutter-troubleshooting)
- [Contributing](#contributing)

---

Laravel Integration
-------------------

[](#laravel-integration)

This section explains how to set up and use the Laravel package to send notifications.

### Laravel Prerequisites

[](#laravel-prerequisites)

- **Laravel Version:** 8+
- **Firebase Project:** Create one in the [Firebase Console](https://console.firebase.google.com/)
- **Service Account Key:** Download the JSON file from your Firebase project settings

### Laravel Installation

[](#laravel-installation)

1. **Install via Composer:**

    ```
    composer require sendfirebase/notificationphp
    ```
2. **Publish the Configuration:**

    ```
    php artisan vendor:publish --provider="SendFireBaseNotificationPHP\Providers\FireBaseNotificationServiceProvider" --tag="config"
    ```
3. **Configure Your Environment:**

    Add these lines to your `.env` file:

    ```
    FIREBASE_PROJECT_ID=your-project-id
    FIREBASE_API_VERSION=v1
    ```
4. **Store Firebase Credentials:**

    Create a directory and move your service account JSON file:

    ```
    mkdir -p storage/app/firebase
    mv path/to/your-service-account.json storage/app/firebase/firebase_credentials.json
    ```

### Laravel Configuration

[](#laravel-configuration)

Ensure your `config/firebase.php` file contains:

```
return [
    'project_id' => env('FIREBASE_PROJECT_ID'),
    'version' => env('FIREBASE_API_VERSION', 'v1'),
    'credentials_file' => storage_path('app/firebase/firebase_credentials.json'),
];
```

### Laravel Usage Examples

[](#laravel-usage-examples)

**1. Send a Notification to a Single User:**

```
use App\Models\User;

public function notifyUser(Request $request)
{
    $firebaseService = app(\SendFireBaseNotificationPHP\Services\FirebaseNotificationService::class);

    $response = $firebaseService->sendNotificationToSingle(
        new User(),          // User model instance
        $request->user_id,   // Target user ID
        "New Message",       // Notification title
        "You have a new notification!", // Notification body
        'fcm_token'          // Column name where FCM token is stored
    );

    return response()->json($response);
}
```

**2. Broadcast a Notification to All Users:**

```
$firebaseService->sendNotificationToAll(
    new User(),           // User model instance
    "Global Alert",       // Notification title
    "Important system update!", // Notification body
    'fcm_token'           // Column name for FCM token
);
```

**3. Send a Notification to a Topic:**

```
$firebaseService->sendNotificationToTopic(
    "all_users",          // Topic name
    "Topic Update",       // Notification title
    "New content available!" // Notification body
);
```

### Laravel Troubleshooting

[](#laravel-troubleshooting)

- **Missing Credentials:**
    Verify that the service account JSON is located in `storage/app/firebase` and that your Firebase project ID in the `.env` file matches your Firebase credentials.
- **General Issues:**
    Check your Laravel logs for errors and review the configuration in `config/firebase.php`.

---

Flutter Integration
-------------------

[](#flutter-integration)

This section details the steps for setting up your Flutter application to receive and handle Firebase notifications.

### Flutter Prerequisites

[](#flutter-prerequisites)

- **Flutter Version:** 3.0+
- **Firebase Project:** Ensure your Firebase project is configured for both Android and iOS
- **Platform-Specific Setup:** For iOS, follow the [Firebase iOS Setup](https://firebase.google.com/docs/ios/setup)

### Flutter Setup &amp; Dependencies

[](#flutter-setup--dependencies)

1. **Add Dependencies:**

    Add the following dependencies to your `pubspec.yaml`:

    ```
    dependencies:
      firebase_messaging: ^15.2.1
      flutter_local_notifications: ^18.0.1
    ```
2. **Basic App Initialization:**

    In your `main.dart`, initialize notifications before running the app:

    ```
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await FbNotifications.initNotifications();
      runApp(MyApp());
    }
    ```

### Flutter Notification Initialization and Handling

[](#flutter-notification-initialization-and-handling)

Implement a mixin to centralize notification setup and handling:

```
mixin FbNotifications on State {
  static late AndroidNotificationChannel channel;
  static late FlutterLocalNotificationsPlugin localNotificationsPlugin;

  // Background Handler
  static Future firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    print("Handling background message: ${message.messageId}");
  }

  // Initialization: Set up channels and permissions
  static Future initNotifications() async {
    FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

    // Android Channel Setup
    channel = const AndroidNotificationChannel(
      'high_importance_channel',
      'Important Notifications',
      importance: Importance.high,
      playSound: true,
    );

    localNotificationsPlugin = FlutterLocalNotificationsPlugin();
    await localNotificationsPlugin
        .resolvePlatformSpecificImplementation()
        ?.createNotificationChannel(channel);

    // iOS Notification Presentation Options
    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  // Request Notification Permissions (especially for iOS)
  Future requestNotificationPermissions() async {
    final settings = await FirebaseMessaging.instance.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('Notifications granted');
    }
  }

  // Foreground Notification Handling for Android
  void initializeForegroundNotificationForAndroid() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = notification?.android;

      if (notification != null && android != null) {
        localNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              icon: '@mipmap/ic_launcher',
            ),
          ),
        );
      }
    });
  }
}
```

3. **Platform-Specific Configurations:**

    - **Android:**
        Update your `AndroidManifest.xml` to include:

        ```

        ```
    - **iOS:**
        Follow the official Firebase iOS setup guide and ensure push notifications are enabled in Xcode.

### Flutter Usage Examples

[](#flutter-usage-examples)

**Subscribing to a Topic:**

```
FirebaseMessaging.instance.subscribeToTopic("all_users");
```

**Handling Background Messages:**

```
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
```

**Handling Notification Taps (when the app is opened via a notification):**

```
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  Navigator.pushNamed(context, '/message');
});
```

**Listening for Token Refresh:**

```
FirebaseMessaging.instance.onTokenRefresh.listen((newToken) {
  // Update your server with the new token
});
```

### Flutter Troubleshooting

[](#flutter-troubleshooting)

- **iOS Notifications Not Showing:**
    Make sure you have completed the iOS setup in Xcode, requested user permissions, and enabled push notifications in your Apple Developer account.
- **Android Notifications Silent:**
    Confirm that the notification channel’s importance is set to high, and verify the metadata in `AndroidManifest.xml`.
- **Token Issues:**
    Ensure that you handle token refresh correctly to keep the server updated with the latest token.

---

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

[](#contributing)

We welcome your contributions to improve the project for both Laravel and Flutter users!

1. **Report Issues:**
    Use GitHub Issues to report bugs or request new features.
2. **Development Setup:**

    ```
    git clone https://github.com/YacoubAl-hardari/firebasenotificationphp.git
    cd firebasenotificationphp
    composer install
    ```
3. **Testing:**Create tests in the `tests/` directory and run:

    ```
    php artisan test
    ```
4. **Coding Standards:**
    Follow the PSR-12 coding style, use PHPStan (level 6), and include PHPDoc comments.
5. **Pull Requests:**
    Fork the repository, create feature branches, and submit a PR with a detailed description of your changes.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance59

Moderate activity, may be stable

Popularity16

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity60

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~35 days

Recently: every ~53 days

Total

7

Last Release

262d ago

PHP version history (2 changes)v1.0.0PHP ^7.4|^8.0|^8.1|^8.2|^8.3

v1.0.5PHP ^7.4|^8.0|^8.1|^8.2|^8.3|^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/1fb3960cf6e949bc5401902a09bf597da5bf4aeaf53c382bb55b1843769c0347?d=identicon)[Yacoub\_Al-haidari](/maintainers/Yacoub_Al-haidari)

---

Top Contributors

[![YacoubAl-hardari](https://avatars.githubusercontent.com/u/94101869?v=4)](https://github.com/YacoubAl-hardari "YacoubAl-hardari (11 commits)")

---

Tags

laravelpackagenotificationsfirebasepush notificationsfirebase notifications

### Embed Badge

![Health badge](/badges/sendfirebase-notificationphp/health.svg)

```
[![Health](https://phpackages.com/badges/sendfirebase-notificationphp/health.svg)](https://phpackages.com/packages/sendfirebase-notificationphp)
```

###  Alternatives

[benwilkins/laravel-fcm-notification

Laravel FCM (Firebase Cloud Messaging) Notification Channel

210964.1k1](/packages/benwilkins-laravel-fcm-notification)[sarfraznawaz2005/laravel-sse

Laravel package to provide Server Sent Events functionality for your app.

474.6k](/packages/sarfraznawaz2005-laravel-sse)

PHPackages © 2026

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