Push Notifications in Laravel with Firebase: A Comprehensive Tutorial

Push Notifications in Laravel with Firebase A Comprehensive Tutorial

Keeping your users engaged in the contemporary interconnected world is one of the essential elements to the success of any web or mobile application. One of the most successful possibilities in this respect is push notifications.

Push notifications are the ideal way to contact clients directly and make them conscious and interested in returning to your application. In this tutorial, you will learn how to send push notifications in an application using Laravel by Firebase Cloud Messaging.

Why Firebase?

Firebase, which is an app development platform for building mobile and web applications by Google, provides suitable tools for the construction and the management of the application.

There are numerous tools available to get the push notifications implemented to devices and applications, but Firebase Cloud Messaging (FCM) is one of the most efficient tools that allow delivering the push notifications on both Android and iOS devices and applications as well as web applications and extensions, which doesn’t affect the battery of the device it operates on.

What makes Laravel even more suitable for an application is its backend strength and Firebase’s strong foundation; so incorporating push notification into a Laravel app is not a herculean task.

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!

Previous Article

A Comprehensive Guide to Laravel Twilio Integration

Next Article

The Power of Visualization: Leveraging AR for Product Display in Ecommerce

View Comments (26)
  1. Invalid service account: The file ‘firebase_credentials.json’ is not readable

    1. 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,
      ]);

      1. 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

  2. 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.

  3. 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?

    1. 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.

  4. Hi – very useful article, it made setting this up very easy. But for the specific user case where might we find the “DeviceToken”

    1. 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);
      });

  5. 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

    1. 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);
      });

        1. 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.

  6. 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

  7. 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’);

    1. 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’
      ]);

    1. 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!

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨