Implement Firebase push notifications in Laravel with PHP 8+ for real-time alerts. Ideal for custom web development and scalable website development services.

Key Points

  • 90% of users consider push notifications helpful for updates.
  • Firebase Cloud Messaging supports 1 M+ messages per second across platforms.
  • Laravel powers 10% of all PHP web apps globally.
Digittrix Blog Author Image

Sr. Web Developer

Sunil M.

3 min read

Passionate web developer with 4+ years of experience creating responsive and high-performing websites.

technology icons of firebase, a mobile phone with notifications and a laravel representing app development tools and services

In today’s digital era, delivering real-time updates is critical for modern applications. Whether you're running an e-commerce store, a healthcare app, or a logistics dashboard, push notifications keep users engaged and informed. In this article, we'll walk you through implementing Firebase Cloud Messaging (FCM) in a Laravel application using PHP 8 or later.

This solution is ideal for businesses seeking reliable website development services or looking to scale their custom web development projects.

Step 1: Set Up Firebase Project

Begin by creating a Firebase project:

  1. Visit the Firebase Console (https://console.firebase.google.com).

  2. Create a new project or use an existing one.

  3. Go to Project Settings → Service accounts → Generate new private key.

  4. Download the JSON file and save it securely at:
    storage/app/firebase/firebase_credentials.json

  5. Note your Project ID (e.g., zajel-7ceb4).

Step 2: Install Google Auth Library

To allow your Laravel app to securely interact with Firebase, install the Google Auth package:

Run the following composer command in your Laravel root directory:

composer require google/auth

This is a standard step in any custom web development project that involves third-party integrations.

Step 3: Configure the Laravel .env File

Update your Laravel environment file (.env) to include Firebase credentials:

                                        FIREBASE_CREDENTIALS=storage/app/firebase/firebase_credentials.json 
FIREBASE_PROJECT_ID=zajel-7ceb4

                                        
                                    

These settings ensure your Laravel application securely authenticates with Firebase using your service account.

Step 4: Laravel Controller for Sending Notifications

Create a controller to handle Firebase messaging logic. This setup uses the Guzzle HTTP client and Google’s Auth library.

                                        <?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Illuminate\Support\Facades\DB;

class ApiController extends Controller
{
    protected $fcmUrl = 'https://fcm.googleapis.com/v1/projects/zajel-7ceb4/messages:send';
    protected $accessToken;

    public function __construct()
    {
        $this->accessToken = $this->getAccessToken();
    }
    // Fetch access token from Firebase service account JSON
    protected function getAccessToken(): string
    {
        $credentialsPath = storage_path('app/firebase/firebase_credentials.json');
        $scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
        $credentials = new ServiceAccountCredentials($scopes, $credentialsPath);
        $token = $credentials->fetchAuthToken();
        return $token['access_token'];
    }

    public function testpushnotification(array $tokens, string $title, string $body): void
    {
        $client = new Client();
        $successCount = 0;
        $failureCount = 0;
        foreach ($tokens as $token) {
            try {
                if (!empty($token)) {
                    $response = $client->post($this->fcmUrl, [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $this->accessToken,
                            'Content-Type'  => 'application/json',
                        ],
                        'json' => [
                            'message' => [
                                'token' => $token,
                                'notification' => [
                                    'title' => $title,
                                    'body'  => $body,
                                ],
                            ],
                        ],
                    ]);
                    $responseBody = json_decode($response->getBody(), true);
                    if (isset($responseBody['error'])) {
                        $failureCount++;
                        echo "Failed for token: $token, Error: {$responseBody['error']['message']}\n";
                    } else {
                        $successCount++;
                    }
                }
            } catch (\GuzzleHttp\Exception\ClientException $e) {
                $responseBody = json_decode($e->getResponse()->getBody(), true);
                if (isset($responseBody['error']['message'])) {
                    DB::table('device_tokens')->where('devicetoken', $token)->delete();
                }
                $failureCount++;
            }
        }
        echo "Push notifications sent: {$successCount} succeeded, {$failureCount} failed.\n";
    }
}
                                        
                                    

Step 5: Trigger Push Notification

To send notifications, you can call the controller method from anywhere in your application (job, command, controller):

                                        <?php
use App\Http\Controllers\ApiController;


public function handle()
{
    $controller = new ApiController();


    $tokens = ['token1', 'token2'];
    $controller->testpushnotification($tokens, 'CLI Push', 'Sent from command line');
}
                                        
                                    

Why Choose Laravel & Firebase?

  • Scalable and secure API-based notifications

  • Seamless integration with mobile and web apps

  • Efficient token management and error handling

  • Perfect for marketing, transactional, and system alerts

Need expert help to integrate this into your project? Hire Laravel Developers at Digittrix to get scalable, secure, and real-time features like Firebase Push implemented efficiently.

Final Words

Integrating Firebase push notifications in Laravel offers immense value for applications that require real-time communication. Whether you run a SaaS platform, mobile app backend, or a data dashboard, this functionality improves user engagement and retention.

At Digittrix, we provide full-scale website development services and custom web development solutions tailored to your business needs. Whether you're launching a new product or modernizing an existing system, our expert Laravel developers can bring your vision to life.

Do you want help implementing this?

Get a summary via Google for

$0

Get Help Now!

Tech Stack & Version

Backend

  • PHP 8
  • Laravel 8

Deployment

  • Apache
  • Nginx
  • VPS
img

©2025Digittrix Infotech Private Limited , All rights reserved.