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
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.
Before diving into the tutorial, make sure you have the following prerequisites in place:
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
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
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.
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']); } }
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']);
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.
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!
Node.js, known for its asynchronous and event-driven architecture, offers a multitude of built-in modules that…
Google has officially rolled out its much-anticipated August 2024 Core Update on August 15, 2024,…
In e-commerce, it's important to understand that it's not just about running an online store.…
In modern web development, building dynamic, interactive front-end applications is essential. Laravel, a powerful PHP…
Laravel, known for its elegant syntax and ease of use, has continually refined its core…
As we continue to innovate and enhance the Magento 2 ecosystem, August 2024 has been…
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');
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
Do you work on a local machine or a live server?
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.
Thank you for positive feedback.
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 ?