Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active May 26, 2026 21:54
Show Gist options
  • Select an option

  • Save devhammed/2f3677bd32840fef9c2bbaa89342e395 to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/2f3677bd32840fef9c2bbaa89342e395 to your computer and use it in GitHub Desktop.
Laravel Aggregated Notification Implementation (https://x.com/akinkunmi/status/2058950199163207690?s=20)
<?php
namespace App\Jobs;
use App\Models\Post;
use App\Models\Like;
use App\Models\User;
use App\Notifications\AggregatedLikeNotification;
use App\Notifications\SingleLikeNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\WithoutRelations;
use Illuminate\Queue\Attributes\DebounceFor;
#[WithoutRelations]
#[DebounceFor(60, maxWait: 120)]
class NotifyOfNewLike implements ShouldQueue
{
use Queueable;
public function __construct(
public Post $post,
) {}
public function debounceId(): string
{
return "post:{$this->post->id}:notify-of-new-like";
}
public function handle(): void
{
$this->post->load([
'user',
'likes' => fn ($q) => $q
->with('user:id,name')
->whereNull('notification_sent_at')
->latest(),
]);
$likes = $this->post->likes;
if ($likes->isEmpty()) {
return;
}
$recipient = $this->post->user;
if ($likes->count() <= 10) {
foreach ($likes as $like) {
$recipient->notify(
new SingleLikeNotification(
post: $this->post,
user: $like->user,
),
);
}
} else {
$firstLike = $likes->first();
$recipient->notify(
new AggregatedLikeNotification(
post: $this->post,
user: $firstLike->user,
othersCount: $likes->count() - 1,
),
);
}
$this->post->likes()
->whereKey($likes)
->update([
'notification_sent_at' => now(),
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment