Cosa sono le notifiche
Il sistema di notifiche di Laravel invia notifiche con un’API unificata su canali multipli: email, SMS, Slack, database, ecc.
Differenza tra Mail e Notification
| Confronto | Mail | Notification |
|---|
| Uso principale | Email HTML ricche | Notifiche brevi |
| Canali | Solo email | Email, DB, Slack, SMS, ecc. |
| Template | Completa libertà | Formato messaggio semplice |
Per notifiche uguali su più canali (es. conferma di pagamento), le Notification sono più adatte.
Creazione di una Notification
php artisan make:notification InvoicePaid
Le classi sono in app/Notifications/. Ogni classe ha un metodo via() e i metodi per generare il messaggio per ciascun canale.
Invio
Con il trait Notifiable
App\Models\User include già Notifiable. Usa notify().
use App\Notifications\InvoicePaid;
$user->notify(new InvoicePaid($invoice));
Il trait Notifiable può essere aggiunto a qualsiasi modello, non solo a User.
Con la facade Notification
Per più utenti:
use Illuminate\Support\Facades\Notification;
Notification::send($users, new InvoicePaid($invoice));
Per inviare subito (saltando la coda) usa sendNow().
Notification::sendNow($developers, new DeploymentCompleted($deployment));
Selezione dei canali
Il metodo via() restituisce l’array dei canali.
public function via(object $notifiable): array
{
return ['mail', 'database'];
}
Puoi differenziare per preferenza utente.
public function via(object $notifiable): array
{
return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database'];
}
Canali principali:
| Canale | Chiave | Descrizione |
|---|
| Email | mail | Notifica via email |
| Database | database | Salva in DB per mostrare in UI |
| Broadcast | broadcast | Notifica realtime (WebSocket) |
| SMS | vonage | SMS via Vonage (ex Nexmo) |
| Slack | slack | Post su canale Slack |
Canale email
Restituisci un MailMessage in toMail().
use Illuminate\Notifications\Messages\MailMessage;
public function toMail(object $notifiable): MailMessage
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->greeting('Ciao!')
->line('Il pagamento della tua fattura è stato confermato.')
->action('Vedi fattura', $url)
->line('Grazie per averci scelto.');
}
Metodi principali:
| Metodo | Descrizione |
|---|
greeting() | Saluto iniziale |
line() | Riga di testo |
action() | Pulsante link |
subject() | Oggetto |
from() | Mittente |
mailer() | Mailer da usare |
Per un messaggio d’errore (pulsante rosso) usa error().
return (new MailMessage)
->error()
->subject('Pagamento fallito')
->line('Il pagamento della fattura è fallito.');
Email Markdown
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
Usa markdown al posto di view in 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,
]);
}
Canale database
Salva le notifiche in DB per mostrarle in app.
Preparazione della tabella
php artisan make:notifications-table
php artisan migrate
Metodo toArray
public function toArray(object $notifiable): array
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
'message' => 'Il pagamento è stato confermato.',
];
}
Salvato in JSON nella colonna data di notifications.
Recupero
$user = App\Models\User::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
echo $notification->data['message'];
}
Solo non lette:
foreach ($user->unreadNotifications as $notification) {
echo $notification->data['message'];
}
Segnare come lette
foreach ($user->unreadNotifications as $notification) {
$notification->markAsRead();
}
$user->unreadNotifications->markAsRead();
$user->unreadNotifications()->update(['read_at' => now()]);
Notifiche in coda
Aggiungi ShouldQueue e Queueable per elaborarle in background.
<?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;
// ...
}
Con ShouldQueue, notify() mette automaticamente in coda.
$user->notify(new InvoicePaid($invoice));
Con delay:
$user->notify(
(new InvoicePaid($invoice))->delay(now()->plus(minutes: 10))
);
Invio simultaneo su più canali
Restituisci più chiavi da via() e definisci i relativi metodi.
<?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
{
return ['mail', 'database'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Pagamento fattura confermato')
->line('Il pagamento della fattura #'.$this->invoice->id.' è stato confermato.')
->action('Vedi fattura', url('/invoice/'.$this->invoice->id));
}
public function toArray(object $notifiable): array
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
];
}
}
Notifiche on-demand
Per notificare utenti senza account, usa Notification::route().
use Illuminate\Support\Facades\Notification;
Notification::route('mail', '[email protected]')
->route('vonage', '5555551212')
->notify(new InvoicePaid($invoice));
Riepilogo
| Obiettivo | Metodo |
|---|
| Crea una notifica | php artisan make:notification ClassName |
| Notifica un utente | $user->notify(new MyNotification()) |
| Notifica più utenti | Notification::send($users, new MyNotification()) |
| Invio email | via() con mail + toMail() |
| Salva in DB | via() con database + toArray() |
| Coda | implementa ShouldQueue |
| Più canali | restituisci più chiavi da via() |