Laravel 10 Send Push Notification to Android Using Firebase

Reading Time: 8 minutes
533 Views

Push notifications on Android devices via Firebase Cloud Messaging (FCM) are a great way to engage users and give real-time updates to your mobile application in Laravel 10. Google FCM is a free, scalable, and dependable messaging service that allows you to deliver notifications to Android, iOS, and web users.

In this tutorial, we will walk you through the process of sending push notifications to Android smartphones in Laravel 10 using Firebase Cloud Messaging. We will look at integrating Firebase into your Laravel application, configuring it, and generating a custom notification that will be provided to your Android app.

Read More: Top 60 FlixHQ Alternatives for Streaming Latest Movies

This article assuming you have the concept of little bit of firebase and it’s console.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Firebase Project and App

First we need to create a project in Firebase console for web application notification. To create project Click here to go to console.

Creating a Firebase Project at Firebase console.

Step #1

Step #2

Step #3

Read More: How To Run Specific Seeder in Laravel 10 Tutorial

Step #4

Back to Firebase Console dashboard panel. We can see we will have a setup icon for android as you can see in this given image. Simply click on that Icon and then the process of Setting up the registration of App will start.

Register a Android App into Firebase Project.

After creating App from here, back to firebase console. Go to App settings by click on gear icon and Click on Cloud messaging tab. You will find the Server key, we need that.

So copy server key.

Successfully, we have now completed the whole process as,

Creating Firebase Project > Register Android App > Copy & Paste Server API Key.

Add API Route

We need to create a POST request api route which will be hit by android device.

Open up the file api.php from /routes folder and add this route into it.

//...
use App\Http\Controllers\NotificationController;

Route::post('send-notification', [NotificationController::class, 'send']);

Next,

Read More: How to Store Data in Cache in Laravel 10 Tutorial

Create Controller & Add Method

Run this artisan command,

$ php artisan make:controller NotificationController

After running this command, you will find a controller NotificationController.php file created inside /app/Http/Controllers folder.

Open up the file and write the given code.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class NotificationController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function send(Request $request)
    {
        return $this->sendNotification($request->device_token, array(
          "title" => "Sample Message", 
          "body" => "This is Test message body"
        ));
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function sendNotification($device_token, $message)
    {
        $SERVER_API_KEY = '<YOUR-SERVER-API-KEY>';
  
        // payload data, it will vary according to requirement
        $data = [
            "to" => $device_token, // for single device id
            "data" => $message
        ];
        $dataString = json_encode($data);
    
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
    
        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
               
        $response = curl_exec($ch);
      
        curl_close($ch);
      
        return $response;
    }
}

The above code will send notification to a single device ID which we will pass into request.

Now,

Let’s say that we want to send notifications to multiple devices.

So, how will we send?

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class NotificationController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function send(Request $request)
    {
        return $this->sendNotification(array(
          $request->device_token1, 
          $request->device_token2,
          $request->device_token3
          //..
        ), array(
          "title" => "Sample Message", 
          "body" => "This is Test message body"
        ));
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function sendNotification($device_tokens, $message)
    {
        $SERVER_API_KEY = '<YOUR-SERVER-API-KEY>';
  
        // payload data, it will vary according to requirement
        $data = [
            "registration_ids" => $device_tokens, // for multiple device ids
            "data" => $message
        ];
        $dataString = json_encode($data);
    
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
    
        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
               
        $response = curl_exec($ch);
      
        curl_close($ch);
      
        return $response;
    }
}

Concept

When we send for a single device, we need to use

$data = [
    "to" => $device_token, // for single device id
    "data" => $message
];

Read More: Laravel 10 Upload and Save XML File Data in Database

And for multiple devices, we have the key as registration_ids. If we want use this registration_ids to send only to a single device, it also works. Only we need to pass a single device token.

$data = [
    "registration_ids" => $device_tokens, // for multiple device ids
    "data" => $message
];

We hope this article helped you to learn about Laravel 10 Send Push Notification to Android Using Firebase Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more