Skip to content

Commit 1451c7c

Browse files
committed
cache notification count, unvalidate on new notification
1 parent e7b3d47 commit 1451c7c

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed

framework/core/src/Notification/Command/ReadAllNotificationsHandler.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ public function handle(ReadAllNotifications $command)
4848

4949
$this->notifications->markAllAsRead($actor);
5050

51+
// Invalidate notification count cache
52+
resolve('cache.store')->forget("user.{$actor->id}.unread_notification_count");
53+
5154
$this->events->dispatch(new ReadAll($actor, Carbon::now()));
5255
}
5356
}

framework/core/src/Notification/Command/ReadNotificationHandler.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ public function handle(ReadNotification $command)
5151

5252
$notification->read_at = Carbon::now();
5353

54+
// Invalidate notification count cache
55+
resolve('cache.store')->forget("user.{$actor->id}.unread_notification_count");
56+
5457
$this->events->dispatch(new Read($actor, $notification, Carbon::now()));
5558

5659
return $notification;

framework/core/src/Notification/Notification.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,12 @@ public static function notify(array $recipients, BlueprintInterface $blueprint)
233233
];
234234
}, $recipients)
235235
);
236+
237+
// Invalidate notification count cache for all recipients
238+
$cache = resolve('cache.store');
239+
foreach ($recipients as $user) {
240+
$cache->forget("user.{$user->id}.unread_notification_count");
241+
}
236242
}
237243

238244
/**

framework/core/src/User/User.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,14 @@ public function getAlertableNotificationTypes()
431431
*/
432432
public function getUnreadNotificationCount()
433433
{
434-
return $this->unreadNotifications()->count();
434+
// Cache notification count for 5 minutes to avoid expensive query on every page load
435+
// Cache is actively invalidated when notifications are marked as read or created,
436+
// so the TTL is mainly a safety net for edge cases (e.g., direct DB updates)
437+
$cacheKey = "user.{$this->id}.unread_notification_count";
438+
439+
return resolve('cache.store')->remember($cacheKey, 300, function () {
440+
return $this->unreadNotifications()->count();
441+
});
435442
}
436443

437444
/**

0 commit comments

Comments
 (0)