To send push notifications to devices and web browsers using Laravel and FCM (Firebase Cloud Messaging), you'll need to follow these steps:

  1. 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.
  2. Install Laravel FCM Package:

    • Install the brozot/laravel-fcm package using Composer:
    bash
    composer require brozot/laravel-fcm
  3. 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, ],
  4. Set Up Environment Variables:

    • Add your Firebase Server Key to the .env file:
    dotenv
    FCM_SERVER_KEY=YOUR_FCM_SERVER_KEY
  5. 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:

    php
    use 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.

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.

Have questions or queries?
Get in Touch