Laravel

Push Notifications in Laravel with Firebase: A Comprehensive Tutorial

In today’s hyper-connected world, staying engaged with your users is crucial for the success of any web or mobile application. One of the most effective ways to achieve this is through push notifications. Push notifications allow you to reach out to your users in real-time, keeping them informed, engaged, and coming back for more. In this tutorial, we’ll delve into how to implement push notifications in a Laravel application using Firebase Cloud Messaging (FCM).

Why Firebase?

Firebase, Google’s mobile and web application development platform, offers a comprehensive set of tools for building and scaling apps. Firebase Cloud Messaging (FCM) is one such tool that provides a reliable and battery-efficient way to deliver push notifications to both Android and iOS devices, as well as web applications. With Laravel’s powerful backend capabilities and Firebase’s robust infrastructure, integrating push notifications into your Laravel application becomes a seamless process.

Prerequisites

Before diving into the tutorial, make sure you have the following prerequisites in place:

  1. Basic understanding of the Laravel framework.
  2. Composer installed globally on your machine.
  3. An active Firebase project. If you haven’t already created one, head over to the Firebase Console ( https://console.firebase.google.com/ ) and create a new project.

Steps to Implement Push Notifications in Laravel using Firebase Cloud Messaging:

Step 1: Setting Up Laravel Project

First, let’s create a new Laravel project or use an existing one:

composer create-project --prefer-dist laravel/laravel firebase-push-notification
cd firebase-push-notification

Step 2: Installing Firebase Admin SDK

Next, we need to install the Firebase Admin SDK for PHP. This SDK allows us to interact with Firebase services from our Laravel application. Install it via Composer:

composer require kreait/firebase-php

Step 3: Configure Firebase Credentials

Navigate to the Firebase Console, select your project, and go to Project Settings > Service accounts. Generate a new private key and download the JSON file containing your service account credentials.

Place this JSON file in your Laravel project’s config directory and rename it to something like firebase_credentials.json.

Step 4: Sending Push Notifications

Now, let’s create a controller to handle push notifications. Run the following artisan command:

php artisan make:controller PushNotificationController

Open app/Http/Controllers/PushNotificationController.php and add the following code:

<?php

namespace App\Http\Controllers;

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

class PushNotificationController extends Controller
{
    public function sendPushNotification()
    {
        $firebase = (new Factory)->withServiceAccount(__DIR__.’/../../../config/firebase_credentials.json’);

        $messaging = $firebase->createMessaging();

        $message = CloudMessage::fromArray([
            'notification' => [
                'title' => 'Hello from Firebase!',
                'body' => 'This is a test notification.'
            ],
            'topic' => 'global'
        ]);

        $messaging->send($message);

        return response()->json(['message' => 'Push notification sent successfully']);
    }
}

Step 5: Define Routes

Next, let’s define a route to trigger the push notification. Open routes/web.php and add the following route definition:

use App\Http\Controllers\PushNotificationController;

Route::get('/send-notification', [PushNotificationController::class, 'sendPushNotification']);

Step 6: Test the Implementation

Now that everything is set up, you can test the implementation by navigating to /send-notification route in your browser. This will trigger the sendPushNotification method in the PushNotificationController, sending a test push notification to all devices subscribed to the ‘global’ topic.

Conclusion:

In this tutorial, we’ve covered the process of integrating Firebase Cloud Messaging (FCM) into a Laravel application for sending push notifications. Push notifications are a powerful tool for engaging users and keeping them informed about important updates or events within your application. With Laravel’s simplicity and Firebase’s reliability, you can easily incorporate push notifications into your projects, enhancing the user experience and driving user engagement.

Unable to implement Firebase Push Notifications within Laravel? Connect with Experienced Laravel Developers.

Happy Coding!

Click to rate this post!
[Total: 37 Average: 3.4]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

View Comments

    • Firebase Cloud Messaging (FCM) no longer supports sending bulk notifications using the registration_ids field, as it has been deprecated.

      Instead, you can send notifications one by one to specific devices using their unique device tokens. Alternatively, a more efficient method is to use topics. By subscribing users to a specific topic, you can send notifications to all devices subscribed to that topic with a single request.

      This way, you can effectively manage and deliver notifications to groups of users. If you have any further questions or need more details, feel free to ask!

    • You can send image like this:

      $message = CloudMessage::fromArray([
      'notification' => [
      'title' => 'Hello from Firebase!',
      'body' => 'This is a test notification.',
      'image' => 'https://example.com/path-to-your-image.jpg' // Add your image URL here
      ],
      'topic' => 'global'
      ]);

  • for ‘firebase_credentials.json’ is not readable error, just add one more ../ to this line :: $firebase = (new Factory)
    ->withServiceAccount(__DIR__.'/../../config/firebase_credentials.json');

    it should be in the end :: $firebase = (new Factory)
    ->withServiceAccount(__DIR__.'/../../../config/firebase_credentials.json');

  • Invalid service account: D:\Srushti\work\news-feed\app\Http\Controllers\Admin/../../config/firebase_credentials.json can not be read: SplFileObject::__construct(D:\Srushti\work\news-feed\app\Http\Controllers\Admin/../../config/firebase_credentials.json): Failed to open stream: No such file or directory

    getting this error idk why ? can anyone help

    • I think you may have a path issue. In Windows paths uses the forward slash "\" but in Ubuntu uses the backward slash "/"

  • bro what about device id in this updated laravel push notification in firbase you only give code to run but were to generate fcm token for user i think it is not cleared article by you or i didnt get it please try to improve this thanks

    • Ok, You can do this below code.



      // Your web app's Firebase configuration
      const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
      appId: "YOUR_APP_ID",
      measurementId: "YOUR_MEASUREMENT_ID"
      };

      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
      const messaging = firebase.messaging();
      messaging.requestPermission()
      .then(function() {
      console.log('Notification permission granted.');
      return messaging.getToken();
      })
      .then(function(token) {
      console.log('Device token:', token); // You can get here device token
      })
      .catch(function(err) {
      console.log('Unable to get permission to notify.', err);
      });

        • This code should be implemented based on the platform you're using:

          For mobile apps: Place the code at the start of your app, ideally on the initial screen when the app is launched.

          For websites: To receive notifications, include the code at the beginning of your website, preferably in the header or the starting part of your site’s code.

  • Hi - very useful article, it made setting this up very easy. But for the specific user case where might we find the "DeviceToken"

    • Ok, You can do this below code.



      // Your web app's Firebase configuration
      const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
      appId: "YOUR_APP_ID",
      measurementId: "YOUR_MEASUREMENT_ID"
      };

      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
      const messaging = firebase.messaging();
      messaging.requestPermission()
      .then(function() {
      console.log('Notification permission granted.');
      return messaging.getToken();
      })
      .then(function(token) {
      console.log('Device token:', token); // You can get here device token
      })
      .catch(function(err) {
      console.log('Unable to get permission to notify.', err);
      });

  • Hey i have done the process you showed. It worked. but i didn't see any notification in my firebase cloud messaging section.
    can you please suggest me anything?

    • You have any device token?
      You can not see the history of the sending notification in Fierbase. You need to manage into your project itself.

  • I looked at so many examples, and they were all missing something. Thanks to you, I solved the problem, thank you very much for this informative sharing.

    • You need to pass that user device token to the withTarget method. For example,

      $deviceToken = $user->device_token;
      $message = CloudMessage::withTarget('token', $deviceToken)
      ->withNotification([
      'title' => 'Title',
      'body' => $message,
      ]);

      • How can i attach a custom field like a action_url, as i can send them using a test message on firebase but i can't seem find a way here on how to send them

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago