Integrating Firebase Push Notifications into Your Laravel Application

Share this post on:

Firebase Cloud Messaging (FCM) is a powerful tool for sending push notifications to your users. In this blog post, we’ll walk through the steps to integrate Firebase push notifications into your Laravel application using the Kreait Laravel Firebase package. This will allow you to send notifications seamlessly from your Laravel backend.

Steps to Integrate Firebase Push Notifications

Step 1: Install the Kreait Firebase Package

First, we need to install the Kreait Laravel Firebase package via Composer. This package provides a convenient way to interact with Firebase services in your Laravel project.

composer require kreait/laravel-firebase

Step 2: Publish the Configuration (Optional)

To customize the Firebase settings, you can publish the configuration file. This step is optional but recommended for more advanced configurations.

php artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config

This will create a config/firebase.php file in your Laravel project, which you can customize as needed.

Step 3: Add Firebase Service Account to Your Project

Download the serviceAccountKey.json file from the Firebase Console:

  1. Go to Firebase Console: Navigate to your Firebase project.
  2. Project Settings: Click the gear icon (⚙️) next to Project Overview and select Project Settings.
  3. Go to Service Accounts Tab: Click on the Service Accounts tab.
  4. a New Private Key: Click the Generate New Private Key button and download the JSON file.

Place the serviceAccountKey.json file in a secure directory, such as storage/app/firebase/serviceAccountKey.json.

Step 4: Set Up the Firebase Credentials in the .env File

Update your .env file to include the path to your Firebase service account credentials:

FIREBASE_CREDENTIALS=/full/path/to/storage/app/firebase/serviceAccountKey.json

Replace /full/path/to/ with the actual path where your serviceAccountKey.json is located.

Step 5: Configure Firebase in config/firebase.php (If published)

If you published the configuration file, update config/firebase.php to use the credentials path from your .env file:

return [
'credentials' => [

        'file' => env('FIREBASE_CREDENTIALS'),

    ],

];

Step 6: Using Firebase Services in Laravel

Now you can use Firebase services such as Cloud Messaging to send push notifications. Here’s an example of how to set up a controller to send notifications:

Create a Controller for Sending Notifications:

use Kreait\Firebase\Factory;

use Kreait\Firebase\Messaging\CloudMessage;

use Kreait\Firebase\Messaging\Notification;

class NotificationController extends Controller

{

    public function sendNotification(Request $request)

    {

        // Initialize Firebase with service account credentials

        $firebase = (new Factory)->withServiceAccount(env('FIREBASE_CREDENTIALS'));

        // Get Firebase Messaging instance

        $messaging = $firebase->createMessaging();

        // Get the device token from the request

        $deviceToken = $request->input('device_token');

        // Ensure the device token is valid

        if (empty($deviceToken)) {

            return response()->json(['error' => 'Device token is missing'], 400);

        }

        // Create the notification

        $notification = Notification::create('Test Title', 'Test Body');

        // Build the message

        $message = CloudMessage::withTarget('token', $deviceToken)->withNotification($notification);

        try {

            // Send the notification

            $messaging->send($message);

            return response()->json(['message' => 'Notification sent successfully']);

        } catch (\Kreait\Firebase\Exception\Messaging\InvalidMessage $e) {

            return response()->json(['error' => 'Invalid message: ' . $e->getMessage()], 400);

        } catch (\Exception $e) {

            return response()->json(['error' => 'Error sending notification: ' . $e->getMessage()], 500);

        }

    }

}

Step 7: Set Up a Route for Sending Notifications

In your routes/web.php or routes/api.php file, add a route for sending notifications:

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

Step 8: Test the Notification

You can test the push notification by making a POST request to /send-notification with a valid device_token in the request body. Use tools like Postman or curl:

curl -X POST http://your-domain.com/send-notification \
-H "Content-Type: application/json" \
-d '{"device_token": "your-device-token"}'

Summary

1. Install: Use Composer to install the kreait/laravel-firebase package.

2. Configure: Place the serviceAccountKey.json file securely and update your .env file.

3. Use: Implement Firebase services such as Cloud Messaging in your Laravel application.

By following these steps, you can successfully integrate Firebase push notifications into your Laravel application and start sending notifications to your users.

Piyush Solanki

PHP Tech Lead & Backend Architect

10+ years experience
UK market specialist
Global brands & SMEs
Full-stack expertise

Core Technologies

PHP 95%
MySQL 90%
WordPress 92%
AWS 88%
  • Backend: PHP, MySQL, CodeIgniter, Laravel
  • CMS: WordPress customization & plugin development
  • APIs: RESTful design, microservices architecture
  • Frontend: React, TypeScript, modern admin panels
  • Cloud: AWS S3, Linux deployments
  • Integrations: Stripe, SMS/OTP gateways
  • Finance: Secure payment systems & compliance
  • Hospitality: Booking & reservation systems
  • Retail: E-commerce platforms & inventory
  • Consulting: Custom business solutions
  • Food Services: Delivery & ordering systems
  • Modernizing legacy systems for scalability
  • Building secure, high-performance products
  • Mobile-first API development
  • Agile collaboration with cross-functional teams
  • Focus on operational efficiency & innovation

Piyush is a seasoned PHP Tech Lead with 10+ years of experience architecting and delivering scalable web and mobile backend solutions for global brands and fast-growing SMEs.

He specializes in PHP, MySQL, CodeIgniter, WordPress, and custom API development, helping businesses modernize legacy systems and launch secure, high-performance digital products.

He collaborates closely with mobile teams building Android & iOS apps, developing RESTful APIs, cloud integrations, and secure payment systems. With extensive experience in the UK market and across multiple sectors, Piyush is passionate about helping SMEs scale technology teams and accelerate innovation through backend excellence.