> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Notifications

> Envoi de notifications par mail, base de données, Slack, etc. via une API unifiée dans Laravel.

## 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**

| Comparaison     | Mail              | Notification                |
| --------------- | ----------------- | --------------------------- |
| Usage principal | E-mail HTML riche | Message d'information court |
| Canaux          | Mail uniquement   | Mail, DB, Slack, SMS, etc.  |
| Templates       | Totalement libres | Format 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`.

```shell theme={null}
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()`.

```php theme={null}
use App\Notifications\InvoicePaid;

$user->notify(new InvoicePaid($invoice));
```

<Info>
  `Notifiable` peut être ajouté à n'importe quel modèle, pas seulement `User`.
</Info>

### Façade Notification

Pour plusieurs destinataires simultanément :

```php theme={null}
use Illuminate\Support\Facades\Notification;

Notification::send($users, new InvoicePaid($invoice));
```

Pour ignorer la queue :

```php theme={null}
Notification::sendNow($developers, new DeploymentCompleted($deployment));
```

## Spécifier les canaux

`via()` retourne les canaux à utiliser.

```mermaid theme={null}
flowchart TD
    A["$user->notify(new InvoicePaid())"] --> B["via() détermine<br>les canaux"]
    B --> C{"Sélection"}
    C --> D["mail<br>toMail()"]
    C --> E["database<br>toArray()"]
    C --> F["broadcast<br>toBroadcast()"]
    C --> G["vonage<br>toVonage()"]
    C --> H["slack<br>toSlack()"]
```

```php theme={null}
public function via(object $notifiable): array
{
    return ['mail', 'database'];
}
```

Vous pouvez changer selon les préférences utilisateur.

```php theme={null}
public function via(object $notifiable): array
{
    return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database'];
}
```

Principaux canaux :

| Canal           | Clé         | Description                             |
| --------------- | ----------- | --------------------------------------- |
| E-mail          | `mail`      | Envoi par e-mail                        |
| Base de données | `database`  | Enregistrement pour affichage dans l'UI |
| Broadcast       | `broadcast` | Notification temps réel (WebSocket)     |
| SMS             | `vonage`    | SMS via Vonage (ex-Nexmo)               |
| Slack           | `slack`     | Publication dans un salon Slack         |

## Canal e-mail

`toMail()` retourne un `MailMessage`.

```php theme={null}
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éthode      | Description               |
| ------------ | ------------------------- |
| `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.

```php theme={null}
return (new MailMessage)
    ->error()
    ->subject('Échec du paiement')
    ->line('Le traitement du paiement a échoué.');
```

### E-mails en Markdown

Générez avec `--markdown`.

```shell theme={null}
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
```

Utilisez `markdown()` dans `toMail`.

```php theme={null}
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

```shell theme={null}
php artisan make:notifications-table

php artisan migrate
```

### `toArray()`

```php theme={null}
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.

```php theme={null}
$user = App\Models\User::find(1);

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

Non lues :

```php theme={null}
foreach ($user->unreadNotifications as $notification) {
    echo $notification->data['message'];
}
```

### Marquer comme lues

```php theme={null}
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 theme={null}
<?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.

```php theme={null}
$user->notify(new InvoicePaid($invoice));
```

Envoi différé :

```php theme={null}
$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 theme={null}
<?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()`.

```php theme={null}
use Illuminate\Support\Facades\Notification;

Notification::route('mail', 'guest@example.com')
    ->route('vonage', '5555551212')
    ->notify(new InvoicePaid($invoice));
```

## Récapitulatif

| Objectif                        | Méthode                                            |
| ------------------------------- | -------------------------------------------------- |
| Créer une Notification          | `php artisan make:notification ClassName`          |
| Notifier un utilisateur         | `$user->notify(new MyNotification())`              |
| Notifier plusieurs utilisateurs | `Notification::send($users, new MyNotification())` |
| Envoyer par mail                | `via()` retourne `mail` + `toMail()`               |
| Enregistrer en base             | `via()` retourne `database` + `toArray()`          |
| Envoyer en queue                | Implémenter `ShouldQueue`                          |
| Multi-canal                     | `via()` retourne plusieurs clés                    |


## Related topics

- [BlueskyManager et HasShortHand](/fr/packages/laravel-bluesky/bluesky-manager.md)
- [Laravel Notification for Discord (Webhook)](/fr/packages/laravel-notification-discord-webhook.md)
- [Canal de notification - Laravel Bluesky](/fr/packages/laravel-bluesky/notification.md)
- [Canal de notification - LINE SDK for Laravel](/fr/packages/laravel-line-sdk/notification.md)
- [Tutoriel - Laravel Console Starter](/fr/packages/laravel-console-starter/tutorial.md)
