To send push notifications to devices and web browsers using Laravel and FCM (Firebase Cloud Messaging), you'll need to follow these steps:
Set Up Firebase Project and Obtain Server Key:
- Create a Firebase project: Go to the Firebase console (https://console.firebase.google.com/) and create a new project.
- Obtain the Server Key: In the Firebase console, navigate to Project Settings > Cloud Messaging. You'll find the Server Key that you'll need to use in your Laravel application to authenticate with FCM.
Install Laravel FCM Package:
- Install the
brozot/laravel-fcm
package using Composer:
bashcomposer require brozot/laravel-fcm
- Install the
Configure Laravel FCM Package:
- Add the Laravel FCM service provider and alias in
config/app.php
:
php'providers' => [ // ... Brozot\LaravelFcm\FcmServiceProvider::class, ], 'aliases' => [ // ... 'FCM' => Brozot\LaravelFcm\Facades\Fcm::class, ],
- Add the Laravel FCM service provider and alias in
Set Up Environment Variables:
- Add your Firebase Server Key to the
.env
file:
dotenvFCM_SERVER_KEY=YOUR_FCM_SERVER_KEY
- Add your Firebase Server Key to the
Send Push Notifications:
- Now you can use the
Fcm
facade to send push notifications from your Laravel application.
For example, sending a push notification to a mobile device:
phpuse FCM; use LaravelFCM\Message\PayloadNotificationBuilder; use LaravelFCM\Message\PayloadDataBuilder; use LaravelFCM\Message\OptionsBuilder; $notificationBuilder = new PayloadNotificationBuilder(); $notificationBuilder->setTitle('Notification Title'); $notificationBuilder->setBody('Hello, this is a push notification'); $dataBuilder = new PayloadDataBuilder(); $dataBuilder->addData(['key1' => 'value1', 'key2' => 'value2']); $optionBuilder = new OptionsBuilder(); $optionBuilder->setTimeToLive(60 * 20); // 20 minutes $notification = $notificationBuilder->build(); $data = $dataBuilder->build(); $option = $optionBuilder->build(); $token = 'DEVICE_REGISTRATION_TOKEN'; // The registration token of the device to send the notification to $response = FCM::sendTo($token, $option, $notification, $data); // You can use $response to check if the notification was sent successfully or if there was an error
For web browsers, you can use JavaScript to interact with FCM and send notifications.
- Now you can use the
Remember to handle errors and check the response from FCM to ensure successful delivery of push notifications.
Please note that this example shows how to send push notifications from a Laravel application to specific devices or web browsers. For web browsers, you'll need to set up the necessary JavaScript code and handle user consent for notifications.