SupportWriter space ↗
← Back to the journal
Laravel

Cache Laravel Dashboard Statistics

Reduce repeated counting with Cache::remember and decide when cached data should refresh.

DAdministrator · 21 Sep 2026 · 1 min read

You are reading a translated version.

A dashboard that counts articles on every visit may repeat the same query unnecessarily. If a short delay is acceptable, caching reduces repeated work.

This example caches global statistics for 60 seconds. It stores a simple array rather than a model with relationships. Configure a cache store first; the database store requires Laravel's cache table.

Implementation example

use App\Models\Post;
use Illuminate\Support\Facades\Cache;

$stats = Cache::remember('dashboard:global:v1', 60, function (): array {
    return [
        'published' => Post::query()
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->count(),
        'drafts' => Post::query()->whereNull('published_at')->count(),
    ];
});

return view('dashboard', ['stats' => $stats]);
// After a successful write; run after commit when using a transaction.
Cache::forget('dashboard:global:v1');
<p>Published: {{ $stats['published'] }}</p>
<p>Drafts: {{ $stats['drafts'] }}</p>

Check the result

Open the dashboard twice and inspect count queries in development. After the cache is populated, subsequent reads reuse it until expiration or invalidation.

Call forget after an article change succeeds. In a transaction, invalidate after commit. For user- or organization-specific statistics, include the owner identity in the key and scope the query accordingly; never share private statistics through a global key.

Scheduled articles can become published without another write. The TTL bounds that delay in the displayed statistics. Choose a TTL according to product needs.

Reference

Official documentation

← Explore more notes