Filament navigation badge showing a pending count
Show a cached count of items awaiting action as a coloured badge on a Filament 4 sidebar entry, with a tooltip and a hide-when-zero rule.
FilamentNavigationfilamentnavigationbadgecache
Code
Needs: filament/filament@^4.0
How it works
What it solves
Moderators and operators should see at a glance where work is waiting. A sidebar badge with the number of pending items does that, but the navigation renders on every page load, so a naive count query runs on every click. This pattern keeps it cheap and informative.
How it works
openCount() is the only place that touches the database. It wraps a count of open and awaiting-review disputes in Cache::remember for 60 seconds, so all three badge hooks share one query and a busy panel runs it at most once a minute.
getNavigationBadge() returns a string, or null when the count is zero, which removes the badge entirely instead of showing a dull "0". Very large counts are capped as "99+". getNavigationBadgeColor() escalates from success to warning to danger as the queue grows, and getNavigationBadgeTooltip() explains the number on hover.
forgetBadge() is a small hook for freshness: call it from the model's saved and deleted events (or an observer) so the number drops right after a moderator resolves a case, rather than waiting for the TTL.
Adapting it
Change the statuses and thresholds, or return a different colour per role. For tenant apps include the tenant id in the cache key. If you do not want caching, remove Cache::remember and keep the query indexed on status.
Pitfalls
- A badge computed per user (for example "assigned to me") needs the user id in the cache key.
- Keep the query as a pure count; do not load models in navigation code.
- Cache stores like
arrayin tests will not share values between requests.
How to use it
- Merge the badge methods into an existing Filament resource (or copy the file and adjust the model).
- Index the
statuscolumn of the table you count. - Add an observer or model events that call
DisputeResource::forgetBadge()when rows change. - Reload the panel: the sidebar item shows the badge when there is pending work.
- Tune thresholds and colours to your own workload.
Licence: DEV3 Snippet Licence. Free to use, change and ship in personal and commercial projects. Attribution is appreciated, not required. Please do not redistribute snippets as a collection.