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: 26 Average: 3.8]
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

  • 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);
      });

  • 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

Node.js | HTTP Module

Node.js, known for its asynchronous and event-driven architecture, offers a multitude of built-in modules that…

2 days ago

Google’s August 2024 Core Update has Fully Rolled Out

Google has officially rolled out its much-anticipated August 2024 Core Update on August 15, 2024,…

2 days ago

Invoicing Guidelines for Independent E-Commerce Businesses

In e-commerce, it's important to understand that it's not just about running an online store.…

4 days ago

Building Dynamic Frontend Applications with Laravel and Alpine.js

In modern web development, building dynamic, interactive front-end applications is essential. Laravel, a powerful PHP…

4 days ago

Exploring Laravel 10’s New Query Builder Enhancements

Laravel, known for its elegant syntax and ease of use, has continually refined its core…

4 days ago

Magento 2 Extensions Digest August 2024 (New Release & Updates)

As we continue to innovate and enhance the Magento 2 ecosystem, August 2024 has been…

6 days ago