Download the PHP package andydefer/laravel-notification without Composer
On this page you can find all versions of the php package andydefer/laravel-notification. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download andydefer/laravel-notification
More information about andydefer/laravel-notification
Files in andydefer/laravel-notification
Package laravel-notification
Short Description Extensible polymorphic notification system for Laravel with multi-channel support (Mail, Database, SMS, WhatsApp, etc.)
License MIT
Informations about the package laravel-notification
Laravel Notification
Système de notifications multi-canaux pour Laravel. Persistance, traçabilité, multiples destinations, planification avancée - avec une architecture extensible.
Table des matières
- Installation
- Pourquoi Laravel Notification ?
- Architecture en un coup d'œil
- Déclarer les canaux d'une entité
- Envoyer une notification
- Envoi immédiat
- Envoi différé
- Envoi planifié
- Envoi récurrent
- Filtrage des destinations avec SendOptions
- NotifiableBuilder - Envoi sans entité
- MessageViewBodyVO - Corps de message basé sur une vue Laravel
- Gestion des tâches
- Statistiques et rapports
- Canaux fonctionnels
- Drivers fonctionnels
- Ping/Pong — Vérification et nettoyage des cibles
- Directives CLI
- Tâches internes
- Créer un canal personnalisé
- Cas d'usage concrets
- Bonnes pratiques
- Trait HasNotifications
- Référence de l'API
Installation
Pourquoi Laravel Notification ?
Le problème : Votre application doit notifier les utilisateurs par email, temps réel (Pusher), Web Push (navigateur), FCM (mobile) et dans la base de données. Chaque médecin a une adresse email professionnelle et une personnelle. Vous devez tracer toutes les notifications pour l'audit, savoir lesquelles ont échoué, et pouvoir consulter l'historique complet.
La solution : Laravel Notification. Un système complet qui orchestre l'envoi sur tous les canaux d'une entité, trace chaque tentative, et permet la planification avancée.
Comparatif rapide
| Besoin | Laravel Notifications (natif) | Laravel Notification |
|---|---|---|
| Plusieurs destinations par canal | ❌ | ✅ |
| Persistance automatique | ❌ (sauf database) | ✅ (tous les canaux) |
| Statut de l'envoi (SENT/FAILED) | ❌ | ✅ |
| Limitation par canal | ❌ | ✅ |
| Métadonnées par destination | ❌ | ✅ |
| Filtrage des destinations par canal | ❌ | ✅ |
| Envoi différé | ⚠️ (via queues) | ✅ (intégré) |
| Envoi récurrent | ⚠️ (via scheduler) | ✅ (intégré) |
| Gestion des tâches (pause/reprise) | ❌ | ✅ |
| Architecture extensible | ⚠️ (complexe) | ✅ (simple) |
| Envoi sans entité Notifiable | ❌ | ✅ (NotifiableBuilder) |
| Corps de message basé vue Laravel | ❌ | ✅ (MessageViewBodyVO) |
| Trait utilitaire pour les modèles | ❌ | ✅ (HasNotifications) |
| Temps réel (Pusher) | ❌ | ✅ |
| Web Push (VAPID) | ❌ | ✅ |
| Firebase Cloud Messaging | ❌ | ✅ |
| Ping/Pong (vérification de validité) | ❌ | ✅ |
| Pruning automatique des cibles invalides | ❌ | ✅ |
En une phrase
Laravel Notifications envoie un message sur un canal défini. Laravel Notification orchestre l'envoi sur tous les canaux d'une entité, trace chaque tentative et permet la planification avancée.
Architecture en un coup d'œil
Composants principaux
| Composant | Rôle |
|---|---|
NotificationService |
Service principal, point d'entrée de l'API |
NotifiableBuilder |
Builder fluide pour envoyer des notifications sans entité |
NotificationSenderProcessor |
Orchestre l'envoi : résolution des routes, filtres, limites |
SendOptions |
Configuration fluide des options d'envoi (canaux, limites, filtres) |
NotificationRouteVO |
Value Object définissant un canal + destination + métadonnées |
AbstractChannel |
Classe de base pour les canaux |
AbstractDriver |
Classe de base pour les drivers |
SendDelayedNotificationTask |
Tâche unique pour les envois différés/planifiés |
SendRecurringNotificationTask |
Tâche récurrente pour les envois périodiques |
MessageViewBodyVO |
Value Object pour corps de message basé sur vue Laravel |
HasNotifications |
Trait utilitaire pour les modèles Eloquent recevant des notifications |
HasPingPong |
Trait utilitaire implémentant PingableInterface |
PingPongAdapter |
Résout le helper ping/pong par modèle |
FcmPingPong |
Helper de vérification pour les appareils FCM |
WebPushPingPong |
Helper de vérification pour les souscriptions Web Push |
PingStatus |
Enum du résultat d'un ping (PONG, INVALID) |
Déclarer les canaux d'une entité
Pour qu'une entité (User, Order, Doctor, etc.) puisse recevoir des notifications, elle doit implémenter l'interface NotifiableInterface.
NotificationRouteVO
Le NotificationRouteVO définit une route de notification :
Envoyer une notification
Envoi immédiat
Envoi différé
Envoi planifié
Envoi récurrent
Filtrage des destinations avec SendOptions
NotifiableBuilder - Envoi sans entité
MessageViewBodyVO - Corps de message basé sur une vue Laravel
Gestion des tâches
Statistiques et rapports
Canaux fonctionnels
| Canal | Nom | Icône | Description | Actif par défaut |
|---|---|---|---|---|
| MailChannel | 📧 | Envoi d'emails via Laravel Mail | ✅ | |
| DatabaseChannel | Base de données | 💾 | Persistance pour la traçabilité | ✅ |
| PusherChannel | Pusher | 📡 | Diffusion temps réel via Pusher | ❌ |
| WebPushChannel | Web Push (VAPID) | 🌐 | Notifications navigateur (W3C Push API) | ❌ |
| FirebaseCloudMessagingChannel | FCM | 🔥 | Notifications mobiles (Android/iOS) | ❌ |
Installation de chaque canal
1. MailChannel — Email
Prérequis : laravel/mail configuré.
Utilisation :
2. DatabaseChannel — Traçabilité
Prérequis : migrations publiées et exécutées.
Utilisation :
Bénéfice : une ligne est insérée pour chaque tentative, avec status, channel, destination, error_message.
3. PusherChannel — Temps réel
Configuration :
Utilisation :
Côté client (Laravel Echo) :
4. WebPushChannel — Notifications navigateur
Génération des clés VAPID :
Cette directive écrit dans .env :
Configuration :
Migration :
Modèle WebPushSubscription :
Utilisation :
Enregistrement côté API :
Service worker côté navigateur :
Écoute côté page :
5. FirebaseCloudMessagingChannel — Mobile
Prérequis :
Configuration :
Modèle FcmDevice :
Enregistrement côté API :
Utilisation :
Drivers fonctionnels
| Driver | Canal | Dépendance externe | Comportement |
|---|---|---|---|
| MailDriver | MailChannel |
Laravel Mail | Utilise Mail::to(...)->send(...) |
| DatabaseDriver | DatabaseChannel |
Base de données | Insère une ligne par notification |
| PusherDriver | PusherChannel |
pusher/pusher-php-server |
Publie un événement via Pusher::trigger() |
| WebPushDriver | WebPushChannel |
minishlink/web-push |
Envoie via W3C Push API + VAPID |
| FirebaseCloudMessagingDriver | FirebaseCloudMessagingChannel |
HTTP client | Publie sur l'API HTTP v1 de FCM |
WebPushDriver — points clés
- Configuration :
WebPushConfigRecord(enabled, subject, public_key, private_key, ttl, urgency, topic). - Métadonnées obligatoires par route :
endpoint,p256dh,auth. - Métadonnées optionnelles :
title,data. - Payload fusionné :
metadata.data+message.data. - Toute erreur d'envoi lève une
RuntimeExceptioncapturée enerror_messageduSendResultRecord.
FirebaseCloudMessagingDriver — points clés
- Configuration :
FirebaseCloudMessagingConfigRecord(enabled, credentials_path, project_id, scope, timeout). - Authentification via OAuth 2.0 (
google/auth). - Résolution du token :
metadata.tokenoudestination. - Payload FCM :
title,body,data,type.
Ping/Pong — Vérification et nettoyage des cibles
Le module Ping/Pong permet de vérifier qu'un appareil FCM ou une souscription Web Push est toujours valide, et de le supprimer automatiquement sinon.
Principe
- Une notification légère (
ping) est envoyée via le canal cible. - Le résultat est interprété :
- Succès → la cible est valide →
PingStatus::PONG,last_seen_atmis à jour. - Échec → la cible est invalide →
PingStatus::INVALID→ suppression.
- Succès → la cible est valide →
- Aucun parsing de message d'erreur n'est effectué : tout échec = invalide.
Contrat PingPongInterface
Enum PingStatus
Trait HasPingPong
À utiliser dans tous les modèles notifiables (FCM, Web Push) :
Le trait délègue la résolution du helper au PingPongAdapter.
PingPongAdapter
Associe chaque modèle à son helper :
Utilisation
Helpers disponibles
| Helper | Canal cible | Suppression automatique |
|---|---|---|
FcmPingPong |
FCM | ✅ via pingOrPrune |
WebPushPingPong |
Web Push | ✅ via pingOrPrune |
Directives CLI
Le package expose plusieurs directives pour l'installation et la maintenance.
notification:generate-vapid
Génère une paire de clés VAPID et l'écrit dans un fichier .env.
Alias : notification:gvk, n:gvk
| Argument / Option | Description |
|---|---|
env |
Chemin du fichier env (défaut : .env) |
--force |
Écrase les clés existantes |
notification:register-prune-fcm
Enregistre la tâche récurrente de nettoyage des appareils FCM invalides.
Alias : notification:rpf, n:rpf
| Argument / Option | Défaut | Description |
|---|---|---|
interval |
1800 |
Intervalle en secondes (minimum 60) |
maxAttempts |
3 |
Nombre maximum de tentatives (minimum 1) |
--force |
false |
Ré-enregistre la tâche même si elle existe |
notification:register-prune-webpush
Enregistre la tâche récurrente de nettoyage des souscriptions Web Push invalides.
Alias : notification:rpwp, n:rpwp
| Argument / Option | Défaut | Description |
|---|---|---|
interval |
1800 |
Intervalle en secondes (minimum 60) |
maxAttempts |
3 |
Nombre maximum de tentatives (minimum 1) |
--force |
false |
Ré-enregistre la tâche même si elle existe |
Tâches internes
Le package utilise andydefer/laravel-task pour planifier et exécuter les tâches différées, récurrentes et de nettoyage.
| Tâche | Type | Rôle |
|---|---|---|
SendDelayedNotificationTask |
Unique | Envoi différé/planifié |
SendRecurringNotificationTask |
Récurrente | Envoi périodique |
PingAndPruneFcmDeviceTask |
Unique | Ping + suppression d'un appareil FCM |
PingAndPruneWebPushSubscriptionTask |
Unique | Ping + suppression d'une souscription Web Push |
PruneFailedFcmNotificationsTask |
Récurrente | Scan des notifications FCM échouées → planification des ping/prune |
PruneFailedWebPushNotificationsTask |
Récurrente | Scan des notifications Web Push échouées → planification des ping/prune |
Fonctionnement du nettoyage
La même logique s'applique à Web Push via PruneFailedWebPushNotificationsTask.
Créer un canal personnalisé
1. Créer le Driver
2. Créer le Channel
3. Créer le Record de Configuration
Cas d'usage concrets
1. Application médicale
2. E-commerce multi-canal
3. Notification temps réel + push
Bonnes pratiques
✅ Injecter le service via le constructeur
✅ Valider les destinations dans l'entité
✅ Utiliser NotifiableBuilder pour les envois directs
✅ Toujours inclure le canal Database
✅ Utiliser les limites par canal
✅ Vérifier périodiquement les cibles push
✅ Gérer les erreurs proprement
Trait HasNotifications
Le trait HasNotifications fournit une API riche pour les modèles Eloquent qui reçoivent des notifications.
Installation
Attributs calculés
| Attribut | Type | Description |
|---|---|---|
unread_notifications_count |
int |
Notifications non lues |
unread_notifications |
Collection |
Notifications non lues |
read_notifications |
Collection |
Notifications lues |
sent_notifications |
Collection |
Notifications envoyées |
pending_notifications |
Collection |
Notifications en attente |
failed_notifications |
Collection |
Notifications échouées |
latest_notifications |
Collection |
10 dernières notifications |
database_notifications |
Collection |
Notifications du canal DatabaseChannel |
has_unread_notifications |
bool |
Y a-t-il des non lues ? |
has_notifications |
bool |
Y a-t-il au moins une notification ? |
Méthodes d'action
| Méthode | Description | Retour |
|---|---|---|
markNotificationAsRead(string $notificationId): bool |
Marque comme lue | bool |
markAllNotificationsAsRead(): int |
Marque toutes comme lues | int |
deleteNotification(string $notificationId): bool |
Soft delete | bool |
deleteAllNotifications(): int |
Supprime tout | int |
deleteReadNotifications(): int |
Supprime les lues | int |
countNotificationsByStatus(NotificationStatus $status): int |
Compte par statut | int |
notificationsByChannel(string $channel, int $limit = 10): Collection |
Par canal | Collection |
Référence de l'API
NotificationService
| Méthode | Description | Retour |
|---|---|---|
withOptions(SendOptions $options): self |
Définit les options | self |
resetOptions(): self |
Réinitialise les options | self |
sendNow(NotifiableInterface, NotificationMessageVO, ?SendNowRecord): SendResultCollection |
Envoi immédiat | SendResultCollection |
sendLater(NotifiableInterface, NotificationMessageVO, ?SendLaterRecord): TaskAliasVO |
Envoi différé | TaskAliasVO |
sendAt(NotifiableInterface, NotificationMessageVO, ?SendAtRecord): TaskAliasVO |
Envoi planifié | TaskAliasVO |
sendRecurring(NotifiableInterface, NotificationMessageVO, ?SendRecurringRecord): TaskAliasVO |
Envoi récurrent | TaskAliasVO |
cancel(string $signature): bool |
Annuler une tâche | bool |
pause(string $signature): bool |
Pause | bool |
resume(string $signature): bool |
Reprise | bool |
changeInterval(string $signature, int $newIntervalSeconds): bool |
Change l'intervalle | bool |
getStats(NotifiableInterface&Model): NotificationStatsVO |
Statistiques | NotificationStatsVO |
getSessionStats(string $sessionId): SessionStatsRecord |
Stats de session | SessionStatsRecord |
SendResultCollection
| Méthode | Description |
|---|---|
getSuccessCount(): int |
Nombre de réussis |
getFailureCount(): int |
Nombre d'échecs |
allSuccess(): bool |
Tous réussis ? |
hasFailures(): bool |
Au moins un échec ? |
filterBySuccess(): self |
Filtre réussis |
filterByFailure(): self |
Filtre échecs |
filterByChannel(string $channelClass): self |
Filtre par canal |
getSuccessfulDestinations(): array |
Destinations réussies |
getFailedDestinations(): array |
Destinations échouées |
NotificationStatsVO
| Propriété | Description |
|---|---|
total: int |
Total |
sent: int |
Nombre de SENT |
failed: int |
Nombre de FAILED |
delivered: int |
Nombre de DELIVERED |
pending: int |
Nombre de PENDING |
success_rate: float |
Taux de succès (%) |
getPercentageSent(): float |
% envoyé |
getPercentageFailed(): float |
% échoué |
isSuccess(): bool |
Tout a réussi |
hasFailures(): bool |
Au moins un échec |
PingStatus
| Case | Description |
|---|---|
PONG |
La cible est valide |
INVALID |
La cible est invalide (à supprimer) |
PingPongInterface
| Méthode | Description |
|---|---|
ping(Model $notifiable): PingStatus |
Envoie un ping |
isAlive(Model $notifiable): bool |
Retourne true si PONG |
pingOrPrune(Model $notifiable): PingStatus |
Ping + suppression si invalide |
Licence
MIT © Andy Defer
All versions of laravel-notification with dependencies
andydefer/laravel-task Version ^4.15.37
pusher/pusher-php-server Version ^7.3
google/apiclient Version ^2.20
andydefer/laravel-nemesis Version ^1.23.3
minishlink/web-push Version ^11.0