Notifications
| Channels | |
| Mail channel | |
| Database channel | |
| Notify users |
Channels
One event often needs several delivery paths: mail for attention and database for history. A Notification class lists its channels in one via method.
Generate the class with artisan, then add one method per channel.
php artisan make:notification OrderShipped
INFO Notification [app/Notifications/OrderShipped.php] created successfully.
Mail channel
The mail channel builds a classic message with subject and lines. Chain short calls on the MailMessage and keep each line plain.
Test with the log driver before sending to real inboxes.
public function via($notifiable) { return ["mail"]; } public function toMail($notifiable) { return (new MailMessage)->subject("Order shipped")->line("Good news."); }
Database channel
The database channel stores a payload row for later display in the app. toArray returns the facts the bell icon needs, like the order id.
The notification stays until the user reads or deletes it.
public function via($notifiable) { return ["database"]; } public function toArray($notifiable) { return [ "order_id" => 7, ]; }
Notify users
Any model with the Notifiable trait can receive notifications. Call notify with the class and Laravel fans the message out to every listed channel.
One call reaches mail and database together, with no extra wiring.
$user->notify(new OrderShipped($order));
Next: Scheduler
Article author: Arthur Isaev