Laravel notifications for comments
Updated: 21th May 2025
Tags: laravel
Laravel Notifications for Comments (The DRY Way)
Laravel offers a powerful notifications system out of the box. In this article, we’ll demonstrate how to use it to notify users of new comments, following a clean, DRY (Don’t Repeat Yourself) approach — ideal for large applications.
1. The Notification Class
We’ll start with a notification class that only stores the commentId
. Some tutorials or tools like ChatGPT may suggest storing the full comment body or author data, but that’s unnecessary if you follow the DRY principle — retrieve that data only when needed.
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
class ReplyPublished extends Notification implements ShouldQueue
{
use Queueable;
protected $comment;
public function __construct($comment)
{
$this->comment = $comment;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'commentId' => $this->comment->id,
];
}
}
2. Displaying Notifications in a Controller
When displaying notifications (e.g., in NotificationsController@index
), we extract the IDs from the notification payload and load all the related comments in one go. This keeps things performant and consistent.
<?php
public function index()
{
$commentIds = [0];
$notifications = auth()->user()
->notifications()
->orderBy('created_at', 'desc')
->paginate(15);
foreach ($notifications as $notification) {
$commentId = $notification->data['commentId'] ?? null;
if ($commentId) {
$commentIds[] = $commentId;
}
}
$comments = Comment::query()
->with('user:id,name,avatar')
->whereIn('id', $commentIds)
->get()
->keyBy('id');
return view('notifications.index', compact('notifications', 'comments'));
}
Note: You can optimize this further by selecting only the necessary columns using
select()
.
3. Automatically Removing Notifications on Comment Deletion
To keep your database clean, you can delete related notifications when a comment is removed. This can be handled in the model’s boot
method:
<?php
class Comment extends Model
{
public static function boot()
{
parent::boot();
static::deleted(function (Comment $comment) {
DB::table('notifications')
->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(data, '$.commentId')) = ?", [$comment->id])
->delete();
});
}
}
4. When to Consider a Custom Notifications Table
This guide uses Laravel’s built-in notifications
table. For larger or high-traffic apps, consider creating a custom notifications table tailored to your needs — it can help with indexing, querying speed, and more efficient storage.