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).
Contents
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:
- Basic understanding of the Laravel framework.
- Composer installed globally on your machine.
- 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:
1 2 |
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:
1 |
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:
1 |
php artisan make:controller PushNotificationController |
Open app/Http/Controllers/PushNotificationController.php and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?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:
1 2 3 |
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!
i change the directory path to
$firebase = (new Factory())
->withServiceAccount(storage_path(‘app/firebase/firebase-credentials.json’));
but now i am getting SSL error :
cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://oauth2.googleapis.com/token
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
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
Hi – very useful article, it made setting this up very easy. But for the specific user case where might we find the “DeviceToken”
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?
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.
how can we send push to specific user ?
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
Invalid service account: The file ‘firebase_credentials.json’ is not readable
You may have to check the permission of the file. File must have 755 or 777 permission to execute the further code.
how do we check it ?