-
-
Save isocroft/3eb7b0d0740ae8f64a8c7386f045f342 to your computer and use it in GitHub Desktop.
Laravel Aggregated Notification Implementation (https://x.com/akinkunmi/status/2058950199163207690?s=20)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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