intermediate 14 min read

Notifications

Mail, database, broadcast notifications, notification channels, and on-demand notifications.

Notifications

// Generate: php artisan make:notification InvoicePaid

namespace App\Notifications;

use App\Models\Invoice;
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(public Invoice $invoice) {}

public function via(object $notifiable): array
{
return ["mail", "database"];
}

public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject("Invoice #{$this->invoice->id} Paid")
->greeting("Hello, {$notifiable->name}!")
->line("Your invoice has been paid.")
->action("View Invoice", url("/invoices/{$this->invoice->id}"))
->line("Thank you for your business!");
}

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

Sending Notifications

// Via notifiable trait
$user->notify(new InvoicePaid($invoice));

// Via Notification facade
Notification::send($users, new InvoicePaid($invoice));

// On-demand notifications
Notification::route("mail", "[email protected]")
->notify(new InvoicePaid($invoice));

Examples

<?php
use App\Notifications\InvoicePaid;
use App\Models\User;

\$user = User::first();
\$user->notify(new InvoicePaid(\$invoice));

// Or to multiple users
\Illuminate\Support\Facades\Notification::send(
    User::where('is_admin', true)->get(),
    new InvoicePaid(\$invoice)
);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.