How to send firebase notification in android devices in laravel

Firebase notification is one of the most common functionality needed when we make web services for mobile devices in laravel. We might have to send firebase notification on some events or custom cases. A lot of opensource packages are available for this purpose. We will use kawancoding/laravel-fcm for sending firebase notifications.

Setup

We can install the package in our laravel application using composer.

composer require kawankoding/laravel-fcm "^0.2.0"

Now, we will register the service provider in our provider array inside config/app.php

 

    'providers' => [
       /*
         * Laravel Framework Service Providers...
         */
        . . . .
        Kawankoding\Fcm\FcmServiceProvider::class,
        . . . . .
    ];

Now, we will publish configuration file for firebase cloud messaging(FCM) where we will add api key later.

php artisan vendor:publish --provider="Kawankoding\Fcm\FcmServiceProvider"

After this, a file called laravel-fcm.php will be created inside config directory like this:

return [

    /**
     * Set your FCM Server Key
     * Change to yours
     */

    'server_key' => env('FCM_SERVER_KEY', ''),

];

Now, go to https://console.firebase.google.com and create new project and setup the project. You can get FCM_SERVER_KEY from there. After that add that key in the .env file.

Also Read: How to make case insensitive search in laravel table ?

Example:

FCM_SERVER_KEY=AAAAnmOusw8:APA91bESq4b4VWWTCnFsx9fT7FnXIgKV16H-gxoFuSrm418ta0sd5qnTwsveN0d7SmbbUnb0_wRk8_j1U22qzQ627G8NBPDGSGYcxZbF3ksJTeI9HmcBQDW7JzgnAKJ9PPbmzuQfjUvQ

This is the complete setup for firebase notification in laravel application. Now, we will go through implementation.

Sending Notifications

At first you have to collect fcm token for all mobile devices that uses our services. We can have database structure something like this.

Customer Devices Table Structure

Column Type
id Integer(Primary Key)
customer_id Integer (Customer Identifier)
fcm_token String
device_id String
auth_token String
created_at Timestamp
updated_at Timestamp

In above structure, customer_id referers to customer using our application. fcm_token is collected when customer logins to our application through api end points. device_id is unique identifier for mobile devices. auth_token will be used to identify individual customer.

Also Read: Common Usage of isset php function in laravel

Now, we will collect fcm tokens from the customer devices. We can add additional constraints to determine wheather customer should be notified or not. Constraints may be customer status, category, anything else. In our example we will notify all customers.

Lets collect fcm tokens.

$recipients = CustomerDevice::pluck('fcm_token')->toArray();

As per specification, we can send firebase notification to 1000 devices at time only. So, we have to divide all these tokens in to chunk of 1000 fcm tokens.

$recipients = array_chunk($recipients, 1000);

Now, we will go through main logic. Here we go :D

 

foreach ($recipients as $chunk){
            fcm()
                ->to($chunk)
                ->data([
                   // data payload
                   .....
                ])
                ->notification([
                  // notification payload
                    ....
                ])->send();
        }

We can send data in two sections.

Notification Payload

In this section, we can only send title and body as key of payload array. This will be the data that appear in the notification appearance.

Data Payload

In this section, we can send our custom data that can be used for variety of purposes like which screen to display while clicking notification, notification listing or something else.

Also Read: Add new column to existing table in Laravel

We can send firebase notification with both type of data like this:

foreach ($recipients as $chunk){
            fcm()
                ->to($chunk)
                ->data([
                    'message' => $message,
                    'image' => $image_url,
                    'url' => $click_url
                ])
                ->notification([
                    'title' => $data['title'],
                ])->send();
        }

In this way, we can send firebase notification to multiple mobile devices in laravel. This is server side implementation only and  we have to implement notification receiver implementation in mobile app as well.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback