PHP code example of tomatophp / fcm-notifications
1. Go to this page and download the library: Download tomatophp/fcm-notifications library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once ('vendor/autoload.php' );
tomatophp / fcm-notifications example snippets
use Illuminate \Notifications \Notification ;
use NotificationChannels \Fcm \FcmChannel ;
use NotificationChannels \Fcm \FcmMessage ;
use NotificationChannels \Fcm \Resources \Notification as FcmNotification ;
class AccountActivated extends Notification
{
public function via ($notifiable)
{
return [FcmChannel::class];
}
public function toFcm ($notifiable) : FcmMessage
{
return (new FcmMessage(notification: new FcmNotification(
title: 'Account Activated' ,
body: 'Your account has been activated.' ,
image: 'http://example.com/url-to-image-here.png'
)))
->data(['data1' => 'value' , 'data2' => 'value2' ])
->custom([
'android' => [
'notification' => [
'color' => '#0A0A0A' ,
],
'fcm_options' => [
'analytics_label' => 'analytics' ,
],
],
'apns' => [
'fcm_options' => [
'analytics_label' => 'analytics' ,
],
],
]);
}
}
class User extends Authenticatable
{
use Notifiable ;
...
public function routeNotificationForFcm ()
{
return $this ->fcm_token;
}
}
class User extends Authenticatable
{
use Notifiable ;
...
public function routeNotificationForFcm ()
{
return $this ->getDeviceTokens();
}
}
$user->notify(new AccountActivated);
FcmMessage::create()
->name('name' )
->token('token' )
->topic('topic' )
->condition('condition' )
->data(['a' => 'b' ])
->custom(['notification' => []]);
public function toFcm (mixed $notifiable) : FcmMessage
{
$client = app(\Kreait\Firebase\Contract\Messaging::class);
return FcmMessage::create()->usingClient($client);
}
namespace App \Listeners ;
use Illuminate \Notifications \Events \NotificationFailed ;
use Illuminate \Support \Arr ;
class DeleteExpiredNotificationTokens
{
public function handle (NotificationFailed $event) : void
{
$report = Arr::get($event->data, 'report' );
$target = $report->target();
$event->notifiable->notificationTokens()
->where('push_token' , $target->value())
->delete();
}
}
protected $listen = [
\Illuminate\Notifications\Events\NotificationFailed::class => [
\App\Listeners\DeleteExpiredNotificationTokens::class,
],
];