A Laravel package to sent notification using Firebase Cloud Messsaging (FCM)
Require the kemalnw/laravel-fcm
package in your composer.json
and update your dependencies:
composer require kemalnw/laravel-fcm
You must publish the config file to define your firebase server key :
php artisan vendor:publish --tag="fcm"
This is the content of the config file published at config/fcm.php
/**
* Define your firebase server key
*/
return [
'server_key' => env('FIREBASE_SERVER_KEY', ''),
];
Use artisan command to create a notification:
php artisan make:notification SomeNotification
Change the via
method so that it becomes:
/**
* Get the notification channels.
*
* @param mixed $notifiable
* @return array|string
*/
public function via($notifiable)
{
return ['fcm'];
}
Add method toFcm
to your notification, and return an instance of Fcm
Facade.
use Fcm;
...
/**
* Get the FCM representation of the notification.
*
* @param mixed $notifiable
* @return void
*/
public function toFcm($notifiable)
{
return Fcm::notification([
'title' => 'Hi!',
'body' => 'This is my first notification.'
])
->timeToLive(604800); // 7 days in second
}
When sending to specific device, the notification system will automatically look for a firebase_uid
property on your notifiable entity. You may customize which firebase token
is used to deliver the notification by defining a routeNotificationForFcm
method on the entity:
...
class User extends Authenticatable
{
use Notifiable;
/**
* Route notifications for the FCM channel.
*
* @param \Illuminate\Notifications\Notification $notification
* @return string
*/
public function routeNotificationForFcm($notification)
{
return $this->firebase_uid;
}
}
When sending to a topic, you may define so within the toFcm
method in the notification:
use Fcm;
...
/**
* Get the FCM representation of the notification.
*
* @param mixed $notifiable
* @return void
*/
public function toFcm($notifiable)
{
return Fcm::notification([
'title' => 'Hi!',
'body' => 'This is my first notification.'
])
->timeToLive(604800) // 7 days in second
->toTopic('topic-name');
}