Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Firebase Push Notification Example Tutorial

Last Updated on May 19, 2024 by

Google Firebase Cloud Messaging (FCM) helps you to send real time push notifications to your laravel 11 applications web and app(mobile) users.

Let’s start to set up google fcm (Firebase Cloud Messaging) push notification to send ios, android and web apps users in laravel:

Step 1: Set Up Firebase

Go to the Firebase Console, and click on “Add project” and follow the instructions to create a new Firebase project.

Now, In your Firebase project, go to the project settings and click on “Add app”, and select the web platform and register your app, and copy the following script:

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_MEASUREMENT_ID"
};

Now, In the Firebase console, go to the Project settings, and navigate to the “Cloud Messaging” tab. And copy under “Project credentials”, find your Server key.

Step 2: Install Firebase PHP Package

Run the following command to Firebase PHP SDK in your application:

composer require kreait/firebase-php

Now run the following command to install http guzzle client:

Install Guzzle HTTP Client

Step 3: Configure Firebase in Laravel

Edit .env File, and add the following firebase configuration in it:

FIREBASE_API_KEY=your_api_key
FIREBASE_AUTH_DOMAIN=your_auth_domain
FIREBASE_DATABASE_URL=your_database_url
FIREBASE_PROJECT_ID=your_project_id
FIREBASE_STORAGE_BUCKET=your_storage_bucket
FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id
FIREBASE_APP_ID=your_app_id
FIREBASE_MEASUREMENT_ID=your_measurement_id
FIREBASE_SERVER_KEY=your_server_key

Step 4: Implementing Push Notification Logic

Create a new service class FirebaseService in the app/Services directory:

namespace App\Services;

use GuzzleHttp\Client;

class FirebaseService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client();
    }

    public function sendNotification($title, $body, $token, $platform = 'android')
    {
        $url = 'https://fcm.googleapis.com/fcm/send';

        $notification = [
            'title' => $title,
            'body' => $body,
        ];

        $data = [
            'to' => $token,
        ];

        if ($platform === 'android') {
            $data['notification'] = $notification;
        } elseif ($platform === 'ios') {
            $data['notification'] = $notification;
            $data['priority'] = 'high';
        } elseif ($platform === 'web') {
            $data['notification'] = $notification;
            $data['webpush'] = [
                'headers' => [
                    'TTL' => '60',
                ],
            ];
        }

        $headers = [
            'Authorization' => 'key=' . env('FIREBASE_SERVER_KEY'),
            'Content-Type' => 'application/json',
        ];

        $response = $this->client->post($url, [
            'headers' => $headers,
            'json' => $data,
        ]);

        return $response->getBody();
    }
}

Step 4: Add Routes

Edit routes/web.php file, and add the following routes into it:

use App\Http\Controllers\NotificationController;

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

Step 5: Send Push Notification

Create a new controller NotificationController in the app/Http/Controllers directory, and create method to send push notification using firebase fcm:

namespace App\Http\Controllers;

use App\Services\FirebaseService;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    protected $firebase;

    public function __construct(FirebaseService $firebase)
    {
        $this->firebase = $firebase;
    }

    public function send(Request $request)
    {
        $title = $request->input('title');
        $body = $request->input('body');
        $token = $request->input('token');
        $platform = $request->input('platform', 'android'); // web, ios, android

        $response = $this->firebase->sendNotification($title, $body, $token, $platform);

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

Step 6: Test Push Notifications

To test the push notification functionality in Postman application.

Send a POST Request for push notification:

  • URL: http://your-domain.com/send-notification
  • Method: POST
  • Body (JSON):json
{
    "title": "Test Notification",
    "body": "This is a test notification",
    "token": "your_device_token"
}

Leave a Comment