Send Firebase push notifications with Laravel php framework.

Overview

FCM Notification Channel for Laravel

Packagist GitHub-tag License Downloads GH-Actions codecov

Send Firebase push notifications with Laravel php framework.

Installation

You can install this package via composer:

composer require ankurk91/fcm-notification-channel

Configuration

This package relies on laravel-firebase package to interact with Firebase services. Here is the minimal configuration you need in your .env file

# relative or full path to the Service Account JSON file
FIREBASE_CREDENTIALS=firebase-credentials.json

You need to create a service account and place the JSON file in your project root.

Usage

You can use the FCM channel in the via() method inside your Notification class:


namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use NotificationChannels\FCM\FCMChannel;
use Kreait\Firebase\Messaging\CloudMessage;

class ExampleNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function via($notifiable): array
    {
        return [FCMChannel::class];
    }

    public function toFCM($notifiable): CloudMessage
    {
        return CloudMessage::new()
            ->withDefaultSounds()
            ->withNotification([
                'title' => 'Hello',
                'body' => 'Message body',
            ])         
            ->withData([
                'key' => 'string value'
            ]);
    }    
}

Prepare your Notifiable model:



namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
       
    /**
    * Assuming that you have a database table which stores device tokens.
    */
    public function deviceTokens(): HasMany
    {
        return $this->hasMany(DeviceToken::class);
    }
    
    public function routeNotificationForFCM(Notification $notification): string|array|null
    {
         return $this->deviceTokens->pluck('token')->toArray();
    }
    
    /**
    * Optional method to determine which message target to use
    * We will use TOKEN type when not specified
    * @see \Kreait\Firebase\Messaging\MessageTarget::TYPES
    */
    public function routeNotificationForFCMTargetType(Notification $notification): ?string
    {
        return \Kreait\Firebase\Messaging\MessageTarget::TOKEN;
    }
    
    /**
    * Optional method to determine which Firebase project to use
    * We will use default project when not specified
    */
    public function routeNotificationForFCMProject(Notification $notification): ?string;
    {
        return config('firebase.default');
    }   
}

Send to a topic or condition

This package is not limited to sending notification to tokens.

You can use Laravel's on-demand notifications to send to a topic or condition or multiple tokens

route('FCMTargetType', MessageTarget::CONDITION) ->notify(new ExampleNotification()); Notification::route('FCM', ['token_1', 'token_2']) ->route('FCMTargetType', MessageTarget::TOKEN) ->notify(new ExampleNotification());">


use Illuminate\Support\Facades\Notification;
use Kreait\Firebase\Messaging\MessageTarget;
use App\Notification\ExampleNotification;

Notification::route('FCM', 'topicA')
    ->route('FCMTargetType', MessageTarget::TOPIC)
    ->notify(new ExampleNotification());

Notification::route('FCM', "'TopicA' in topics")
    ->route('FCMTargetType', MessageTarget::CONDITION)
    ->notify(new ExampleNotification());

Notification::route('FCM', ['token_1', 'token_2'])
    ->route('FCMTargetType', MessageTarget::TOKEN)
    ->notify(new ExampleNotification());

Events

You can consume Laravel's inbuilt notification events



namespace App\Providers;

use Illuminate\Notifications\Events;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Events\NotificationSent::class => [
            \App\Listeners\FCMNotificationSent::class,
        ],
        Events\NotificationFailed::class => [
            \App\Listeners\FCMNotificationFailed::class,
        ],
    ];    
}

Here is the example of the failed event listener class



namespace App\Listeners;

use App\Models\User;
use NotificationChannels\FCM\FCMChannel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Events\NotificationFailed;

class FCMNotificationFailed implements ShouldQueue
{
    public function handle(NotificationFailed $event)
    {
        if ($event->channel !== FCMChannel::class) {
            return;
        }

        /** @var User $user */
        $user = $event->notifiable;
        
        //todo Delete invalid device tokens from database
    }
}

Read more about validating device tokens here

Additionally, you may want to ignore this exception in your app/Exceptions/Handler.php

protected $dontReport = [
    \NotificationChannels\FCM\Exception\InvalidRecipientException::class,
];

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Security

If you discover any security issue, please email pro.ankurk1[at]gmail[dot]com instead of using the issue tracker.

Attribution

The package is based on this PR

License

This package is licensed under MIT License.

You might also like...
Standalone PHP library for easy devices notifications push.

NotificationPusher Standalone PHP library for easy devices message notifications push. Feel free to contribute! Thanks. Contributors Cédric Dugat (Aut

This package makes it easy to send notifications using RocketChat with Laravel 9.0+.

laravel-rocket-chat-notifications Introduction This package makes it easy to send notifications using RocketChat with Laravel 9.0+. Contents Installat

:computer: Send notifications to your desktop directly from your PHP script
:computer: Send notifications to your desktop directly from your PHP script

About JoliNotif JoliNotif is a cross-platform PHP library to display desktop notifications. It works on Linux, Windows or MacOS. Requires PHP = 7.2 (

Notifications in PHP (notify-send, growl, etc) like that.

#Nod Notifications in PHP (notify-send, growl, etc) like that. ##Examples Letting Nod figure out the best Adapter to use (not recommend ATM, only work

This package allows you to send notifications to Microsoft Teams.
This package allows you to send notifications to Microsoft Teams.

Teams connector This package allows you to send notifications to Microsoft Teams. Installation You can install the package using the Composer package

Service that helps you to send notifications for a series of failed exceptions.

Laravel Failure Notifier This package helps you to track your exceptions and do what you want to do with them such as sending an SMS or and Email. You

It's Pimcore Bundle to send notifications to Google Chat, Slack or Email from admin panel inside Pimcore
It's Pimcore Bundle to send notifications to Google Chat, Slack or Email from admin panel inside Pimcore

Send notifications to Discord, Google Chat, Slack and more from Pimcore It's Pimcore Bundle to send notifications to Discord, Google Chat, Slack, Tele

Laravel FCM (Firebase Cloud Messaging) Notification Channel

Laravel FCM Notification Laravel FCM (Firebase Cloud Messaging) Notification Channel Use this package to send push notifications via Laravel to Fireba

Implementation of Firebase Cloud Messaging HTTP v1 API in PHP

php-fcm-v1 php-fcm-v1 is an PHP implementation of FCM HTTP v1 API What is different compared to others FCM Libraries? Most of other libraries are impl

Comments
  • Send an FCM directly to a user without the notification model

    Send an FCM directly to a user without the notification model

    Hello,

    is it possible to use your package to send an FCM directly to a user device_ID without passing through the notification model and the via method and the notifiable trait?

    I just want to be able to send a raw message using my own models and architecture.

    Thanks a lot.

    opened by nicolasvahidzein 3
Releases(1.3.1)
Owner
Ankur Kumar
Open Source Fanatic | Tinkerer | Spotify Addict
Ankur Kumar
This package makes it easy to send web push notifications with Laravel.

Web push notifications channel for Laravel This package makes it easy to send web push notifications with Laravel. Installation You can install the pa

Laravel Notification Channels 564 Jan 3, 2023
A PHP Library to easily send push notifications with the Pushwoosh REST Web Services.

php-pushwoosh A PHP Library to easily send push notifications with the Pushwoosh REST Web Services. First sample, creating a Pushwoosh message // Crea

gomoob 63 Sep 28, 2022
Send push notifications to apple devices (iPhone, iPad, iPod).

Apple Apn Push Send push notifications to apple devices (iPhone, iPad, iPod). Support authenticators: Certificate Json Web Token Supported protocols:

Vitaliy Zhuk 157 Dec 1, 2022
WebPush can be used to send notifications to endpoints which server delivers Web Push

WebPush can be used to send notifications to endpoints which server delivers Web Push notifications as described in the Web Push protocol. As it is standardized, you don't have to worry about what server type it relies on.

null 1.5k Jan 7, 2023
Push Notifications using Laravel

laravel-push-notification Push Notifications using Laravel PushNotification::send(['deviceToken1', 'deviceToken2',..], 'Notification Message', 'Action

Webelight Solutions 26 Jul 22, 2022
Laravel package to enable sending push notifications to devices

Laravel Push Notification Package to enable sending push notifications to devices Installation Update your composer.json file to include this package

Davi Nunes 1.2k Sep 27, 2022
Standalone PHP library for easy devices notifications push.

NotificationPusher Standalone PHP library for easy devices message notifications push. Feel free to contribute! Thanks. Contributors Cédric Dugat (Aut

Cédric Dugat 1.2k Jan 3, 2023
Takes care of Apple push notifications (APNS) in your PHP projects.

Notificato Notificato takes care of push notifications in your PHP projects. Italian: notificato è: participio passato English: notified Why use Notif

Mathijs Kadijk 223 Sep 28, 2022
Push notifications Library for PHP

Push notifications Library for PHP Supported Protocols Protocol Supported Driver Options APNs (Token Based) ✓ APNs\Token APNs\Token\Option APNs (Certi

Norifumi SUNAOKA 3 Dec 14, 2022
Takes care of Apple push notifications (APNS) in your PHP projects.

Notificato Notificato takes care of push notifications in your PHP projects. Italian: notificato è: participio passato English: notified Why use Notif

Mathijs Kadijk 223 Sep 28, 2022