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

# Notificaties (Notifications)

> Leer hoe je met Laravels notificatiesysteem in één keer naar meerdere kanalen verstuurt, zoals e-mail, database en Slack.

## Wat is een Notification

Het notificatiesysteem (Notification) van Laravel is een mechanisme om via een uniforme API notificaties te versturen naar meerdere bezorgkanalen, zoals e-mail, sms, Slack en de database.

**Het verschil tussen Mail en Notification**

| Vergelijking          | Mail               | Notification                                |
| --------------------- | ------------------ | ------------------------------------------- |
| Belangrijkste gebruik | Rijke HTML-e-mails | Korte informatieve meldingen                |
| Bezorgkanalen         | Alleen e-mail      | Meerdere: e-mail, database, Slack, sms enz. |
| Templates             | Volledig vrij      | Eenvoudig berichtformaat                    |

Wil je dezelfde melding naar meerdere kanalen sturen, zoals een bevestiging dat een factuur is betaald, dan is een Notification de juiste keuze.

## Een Notification-klasse maken

Genereer een klasse met het Artisan-commando `make:notification`.

```shell theme={null}
php artisan make:notification InvoicePaid
```

De gegenereerde klasse komt in de directory `app/Notifications/` te staan. De klasse bevat een `via()`-methode en methoden die per kanaal het bericht genereren.

## Notificaties versturen

### Met de Notifiable-trait

`App\Models\User` bevat standaard de `Notifiable`-trait. Met de methode `notify()` verstuur je een notificatie.

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

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

<Info>
  De `Notifiable`-trait is niet beperkt tot het `User`-model; je kunt hem aan elk model toevoegen.
</Info>

### Met de Notification-facade

Om naar meerdere gebruikers tegelijk te versturen, gebruik je de `Notification`-facade.

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

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

Wil je direct versturen (de queue overslaan), gebruik dan `sendNow()`.

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

## Bezorgkanalen opgeven

De `via()`-methode geeft een array terug met de te gebruiken kanalen.

```mermaid theme={null}
flowchart TD
    A["$user->notify(new InvoicePaid())"] --> B["via() bepaalt<br>de kanalen"]
    B --> C{"Kanaalkeuze"}
    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'];
}
```

Je kunt de kanalen ook laten afhangen van de voorkeuren van de gebruiker.

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

De belangrijkste beschikbare kanalen zijn:

| Kanaal    | Sleutel     | Beschrijving                                   |
| --------- | ----------- | ---------------------------------------------- |
| E-mail    | `mail`      | Verstuurt de notificatie per e-mail            |
| Database  | `database`  | Slaat op in de database voor weergave in de UI |
| Broadcast | `broadcast` | Realtime notificaties (WebSocket)              |
| Sms       | `vonage`    | Verstuurt sms via Vonage (voorheen Nexmo)      |
| Slack     | `slack`     | Plaatst een bericht in een Slack-kanaal        |

## Notificaties via het mailkanaal

De methode `toMail()` geeft een `MailMessage`-instantie terug.

```php theme={null}
use Illuminate\Notifications\Messages\MailMessage;

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

    return (new MailMessage)
        ->greeting('Hallo!')
        ->line('We hebben de betaling van je factuur ontvangen.')
        ->action('Factuur bekijken', $url)
        ->line('Bedankt voor je gebruik van onze dienst.');
}
```

De belangrijkste methoden van `MailMessage` zijn:

| Methode      | Beschrijving                |
| ------------ | --------------------------- |
| `greeting()` | De begroeting aan het begin |
| `line()`     | Eén regel tekst in de body  |
| `action()`   | Een knop met link           |
| `subject()`  | Het onderwerp               |
| `from()`     | Het afzenderadres           |
| `mailer()`   | De te gebruiken mailer      |

Meld je een fout, voeg dan de methode `error()` toe: de knop wordt dan rood.

```php theme={null}
return (new MailMessage)
    ->error()
    ->subject('Betaling mislukt')
    ->line('De betaling van je factuur kon niet worden verwerkt.');
```

### Markdown-notificatiemails

Je kunt ook rijke e-mails in Markdown-formaat gebruiken. Genereer de klasse met de optie `--markdown`.

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

In plaats van `toMail()` gebruik je `toMarkdownMail()`.

```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,
        ]);
}
```

## Notificaties via het databasekanaal

Met het databasekanaal sla je notificaties op in de database en toon je ze in de UI van je app.

### De tabel voorbereiden

Maak eerst de tabel `notifications` aan.

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

php artisan migrate
```

### De toArray-methode definiëren

De methode `toArray()` geeft de op te slaan data als array terug.

```php theme={null}
public function toArray(object $notifiable): array
{
    return [
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
        'message' => 'We hebben de betaling van je factuur ontvangen.',
    ];
}
```

Deze data wordt in JSON-formaat opgeslagen in de kolom `data` van de tabel `notifications`.

### Notificaties ophalen

Met de `notifications`-relatie die de `Notifiable`-trait biedt, haal je notificaties op.

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

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

Wil je alleen de ongelezen notificaties ophalen, gebruik dan `unreadNotifications`.

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

### Als gelezen markeren

Met `markAsRead()` markeer je een notificatie als gelezen.

```php theme={null}
// Individueel als gelezen markeren
foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
}

// Allemaal tegelijk als gelezen markeren
$user->unreadNotifications->markAsRead();

// In bulk bijwerken met een query
$user->unreadNotifications()->update(['read_at' => now()]);
```

## Notificaties via de queue verwerken

Duurt het versturen van een notificatie lang, voeg dan de interface `ShouldQueue` en de trait `Queueable` toe om de notificatie via de queue te verwerken. In klassen die je met `make:notification` genereert, zijn deze al geïmporteerd.

```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;

    // ...
}
```

Implementeer je `ShouldQueue`, dan wordt de notificatie automatisch in de queue geplaatst zodra je `notify()` aanroept.

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

Vertraagd versturen kan ook.

```php theme={null}
$user->notify(
    (new InvoicePaid($invoice))->delay(now()->plus(minutes: 10))
);
```

## Tegelijk naar meerdere kanalen versturen

Door in de `via()`-methode meerdere kanalen terug te geven en voor elk kanaal een methode te definiëren, verstuur je dezelfde notificatie tegelijk naar meerdere kanalen.

```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
    {
        // Zowel naar e-mail als naar de database versturen
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('We hebben de betaling van je factuur ontvangen')
            ->line('We hebben de betaling van factuur #'.$this->invoice->id.' ontvangen.')
            ->action('Factuur bekijken', url('/invoice/'.$this->invoice->id));
    }

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

## On-demand notificaties

Wil je ook notificaties sturen naar mensen zonder account in je app, gebruik dan `Notification::route()`.

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

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

## Samenvatting

| Wat je wilt doen                  | Hoe                                                       |
| --------------------------------- | --------------------------------------------------------- |
| Een Notification maken            | `php artisan make:notification ClassName`                 |
| Een gebruiker notificeren         | `$user->notify(new MyNotification())`                     |
| Meerdere gebruikers notificeren   | `Notification::send($users, new MyNotification())`        |
| Per e-mail versturen              | Geef `mail` terug in `via()` en definieer `toMail()`      |
| Opslaan in de database            | Geef `database` terug in `via()` en definieer `toArray()` |
| Asynchroon versturen via de queue | Implementeer `ShouldQueue`                                |
| Naar meerdere kanalen versturen   | Geef meerdere sleutels terug in `via()`                   |


## Related topics

- [BlueskyManager en HasShortHand](/nl/packages/laravel-bluesky/bluesky-manager.md)
- [Laravel Notification for Discord(Webhook)](/nl/packages/laravel-notification-discord-webhook.md)
- [Laravel Telescope](/nl/telescope.md)
- [Notificatiekanaal - Laravel Bluesky](/nl/packages/laravel-bluesky/notification.md)
- [Notificatiekanaal - LINE SDK for Laravel](/nl/packages/laravel-line-sdk/notification.md)
