Laravel Notifications
Lesson 33 of 33 in the Laravel learning path.
How do I notify a user on the database channel and by mail from one class?
A notification describes one message and the channels that deliver it. The Notifiable trait gives a user notify().
Mail alone does not fill an in-app inbox. One class can list database and mail without two controller calls.
Syntax & Parameters
$user->notify(new LessonPublishedNotification($lesson));
Example
<?php
namespace App\Notifications;
use App\Models\Lesson;
use Illuminate\Notifications\Notification;
class LessonPublishedNotification extends Notification
{
public function __construct(public Lesson $lesson) {}
public function via(object $notifiable): array
{
return ['database'];
}
public function toArray(object $notifiable): array
{
return [
'lesson_id' => $this->lesson->id,
'title' => $this->lesson->title,
];
}
}
Expected Output
A row in notifications whose data JSON contains lesson_id and title. The header can list unread notifications for that user.
Line-by-Line Walkthrough
- The notification holds the lesson.
- via lists the database channel only in this sample.
- toArray is the payload stored in the notifications table.
- The payload is an id and a title, not the whole model graph.
- The user model needs the Notifiable trait.
- notify() writes the row.
- A mail channel would add a toMail method.
- Queue the notification if delivery can wait.
Common Pitfalls & Security
Read the limits before you copy this.
- via that returns mail without toMail throws when it sends.
- Storing the entire lesson model in the array bloats the table.
- Notifying an address from the request lets a user spam someone else.
- Database notifications still need a UI. The row alone is invisible.
Best Practices & Modern Standards
Keep the payload small: an id, a title, and a URL you will rebuild.
Notify the authenticated user’s related users through a query you control, not through a posted email list.
Real-World Use
Publishing a lesson writes a database notification for the instructor. The bell marks it read. Mail can be added later by listing another channel.
Frequently Asked Questions
Which table stores them?
notifications, from the Laravel migration for database notifications.
How do I mark one read?
Call markAsRead on the notification model for that user.
Can I queue it?
Yes. Implement ShouldQueue on the notification class.
Who can be notified?
Any model that uses Notifiable, usually User.