Handle FCM notification failures
masterWhen an FCM notification fails, Laravel dispatches the Illuminate\Notifications\Events\NotificationFailed event. You can listen for this event to perform cleanup tasks, such as deleting expired or invalid FCM tokens from your database.
namespace App\
Listeners;
use Illuminate\Notifications\Events\NotificationFailed;
use Illuminate\Support\Arr;
class DeleteExpiredNotificationTokens
{
public function handle(NotificationFailed $event): void
{
if ($event->channel == \NotificationChannels\Fcm\FcmChannel::class) {
$report = Arr::get($event->data, 'report');
$target = $report->target();
$event->notifiable->notificationTokens()
->where('push_token', $target->value())
->delete();
}
}
}Register the listener in your EventServiceProvider:
protected $listen = [
\Illuminate\Notifications\Events\NotificationFailed::class => [
\App\Listeners\DeleteExpiredNotificationTokens::class,
],
];