Passer au contenu principal

Qu’est-ce qu’une Notification

Le système de Notification de Laravel permet d’envoyer des notifications via plusieurs canaux (mail, SMS, Slack, base…) avec une API unifiée. Différences Mail vs Notification
ComparaisonMailNotification
Usage principalE-mail HTML richeMessage d’information court
CanauxMail uniquementMail, DB, Slack, SMS, etc.
TemplatesTotalement libresFormat de message simple
Pour envoyer la même information sur plusieurs canaux (ex. confirmation de paiement), Notification est adaptée.

Créer une Notification

Utilisez make:notification.
php artisan make:notification InvoicePaid
Le fichier est créé dans app/Notifications/. Il expose via() et les méthodes de génération de message par canal.

Envoi

Trait Notifiable

App\Models\User inclut le trait Notifiable par défaut. Envoyez avec notify().
use App\Notifications\InvoicePaid;

$user->notify(new InvoicePaid($invoice));
Notifiable peut être ajouté à n’importe quel modèle, pas seulement User.

Façade Notification

Pour plusieurs destinataires simultanément :
use Illuminate\Support\Facades\Notification;

Notification::send($users, new InvoicePaid($invoice));
Pour ignorer la queue :
Notification::sendNow($developers, new DeploymentCompleted($deployment));

Spécifier les canaux

via() retourne les canaux à utiliser.
public function via(object $notifiable): array
{
    return ['mail', 'database'];
}
Vous pouvez changer selon les préférences utilisateur.
public function via(object $notifiable): array
{
    return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database'];
}
Principaux canaux :
CanalCléDescription
E-mailmailEnvoi par e-mail
Base de donnéesdatabaseEnregistrement pour affichage dans l’UI
BroadcastbroadcastNotification temps réel (WebSocket)
SMSvonageSMS via Vonage (ex-Nexmo)
SlackslackPublication dans un salon Slack

Canal e-mail

toMail() retourne un MailMessage.
use Illuminate\Notifications\Messages\MailMessage;

public function toMail(object $notifiable): MailMessage
{
    $url = url('/invoice/'.$this->invoice->id);

    return (new MailMessage)
        ->greeting('Bonjour !')
        ->line('Votre paiement a été confirmé.')
        ->action('Voir la facture', $url)
        ->line('Merci pour votre confiance.');
}
Méthodes principales :
MéthodeDescription
greeting()Salutation d’introduction
line()Une ligne de corps
action()Bouton d’action
subject()Sujet
from()Adresse de l’expéditeur
mailer()Mailer à utiliser
Pour une erreur, error() colore le bouton en rouge.
return (new MailMessage)
    ->error()
    ->subject('Échec du paiement')
    ->line('Le traitement du paiement a échoué.');

E-mails en Markdown

Générez avec --markdown.
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
Utilisez markdown() dans toMail.
use Illuminate\Notifications\Messages\MailMessage;

public function toMail(object $notifiable): MailMessage
{
    return (new MailMessage)
        ->markdown('mail.invoice.paid', [
            'url' => url('/invoice/'.$this->invoice->id),
            'invoice' => $this->invoice,
        ]);
}

Canal base de données

Le canal database enregistre les notifications en base, pour affichage dans votre UI.

Table

php artisan make:notifications-table

php artisan migrate

toArray()

public function toArray(object $notifiable): array
{
    return [
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
        'message' => 'Paiement confirmé.',
    ];
}
Ces données sont sérialisées en JSON dans la colonne data de notifications.

Lire les notifications

Via la relation notifications du trait.
$user = App\Models\User::find(1);

foreach ($user->notifications as $notification) {
    echo $notification->type;
    echo $notification->data['message'];
}
Non lues :
foreach ($user->unreadNotifications as $notification) {
    echo $notification->data['message'];
}

Marquer comme lues

foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
}

$user->unreadNotifications->markAsRead();

$user->unreadNotifications()->update(['read_at' => now()]);

Notifications en queue

Pour les traitements longs, implémentez ShouldQueue et utilisez le trait Queueable. Ils sont inclus par défaut par make:notification.
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    // ...
}
Un simple notify() met alors automatiquement en file.
$user->notify(new InvoicePaid($invoice));
Envoi différé :
$user->notify(
    (new InvoicePaid($invoice))->delay(now()->plus(minutes: 10))
);

Envoi vers plusieurs canaux

Il suffit de retourner plusieurs canaux dans via() et de définir les méthodes correspondantes.
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        private readonly Invoice $invoice,
    ) {}

    public function via(object $notifiable): array
    {
        // Mail + base
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Paiement confirmé')
            ->line('Paiement de la facture #'.$this->invoice->id.' confirmé.')
            ->action('Voir la facture', url('/invoice/'.$this->invoice->id));
    }

    public function toArray(object $notifiable): array
    {
        return [
            'invoice_id' => $this->invoice->id,
            'amount' => $this->invoice->amount,
        ];
    }
}

Notifications à la demande

Pour envoyer à quelqu’un sans compte : Notification::route().
use Illuminate\Support\Facades\Notification;

Notification::route('mail', '[email protected]')
    ->route('vonage', '5555551212')
    ->notify(new InvoicePaid($invoice));

Récapitulatif

ObjectifMéthode
Créer une Notificationphp artisan make:notification ClassName
Notifier un utilisateur$user->notify(new MyNotification())
Notifier plusieurs utilisateursNotification::send($users, new MyNotification())
Envoyer par mailvia() retourne mail + toMail()
Enregistrer en basevia() retourne database + toArray()
Envoyer en queueImplémenter ShouldQueue
Multi-canalvia() retourne plusieurs clés
Dernière modification le 13 juillet 2026