Send Firebase push notifications with Laravel php framework.

Last update: Jun 29, 2022

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.

GitHub

https://github.com/ankurk91/fcm-notification-channel
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

Jun 15, 2022

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

May 27, 2022

: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 (

Jun 26, 2022

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

Mar 26, 2019

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

May 6, 2022

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

Jun 30, 2022

ApnsPHP: Apple Push Notification & Feedback Provider

ApnsPHP: Apple Push Notification & Feedback Provider

ApnsPHP: Apple Push Notification & Feedback Provider A full set of open source PHP classes to interact with the Apple Push Notification service for th

May 29, 2022

Laravel Security Notifications

This package adds security notifications to warn your users when significant security events occur so that they aren't the next victim of an attacker.

Feb 8, 2022

Laravel package to launch toast notifications.

Laravel package to launch toast notifications.

Laravel package to launch toast notifications. This package provides assistance when using toast notifications. Using the iziTOAST package, which allo

Mar 14, 2022
Comments
  • 1. 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.

    Reviewed by nicolasvahidzein at 2022-06-27 07:34
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

Jun 30, 2022
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

Jun 17, 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:

Apr 26, 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.

Jun 20, 2022
Push Notifications using Laravel
Push Notifications using Laravel

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

Apr 6, 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

Jun 16, 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

Jun 15, 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

Jun 27, 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

Mar 25, 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

Apr 17, 2022