Laravel
Intermediate
Auth & Jobs
· 6 min read
Laravel Cache for a Catalog Count
Lesson 21 of 33 in the Laravel learning path.
How do I cache an expensive count without serving it forever?
Cache::remember returns the stored value or runs the closure and stores the result.
The homepage count does not need a fresh query on every hit, but it must expire so a new lesson shows up.
Syntax & Parameters
Cache::remember('lessons.published-count', 300, fn () => ...);
Example
<?php
namespace App\Services;
use App\Models\Lesson;
use Illuminate\Support\Facades\Cache;
class CatalogStats
{
public function publishedCount(): int
{
return Cache::remember('lessons.published-count', 300, function () {
return Lesson::query()->whereNotNull('published_at')->count();
});
}
public function forget(): void
{
Cache::forget('lessons.published-count');
}
}
Expected Output
The first homepage hit queries the count. The next hits for five minutes reuse it. Publishing a lesson forgets the key.
Line-by-Line Walkthrough
- The key names the value.
- 300 is the lifetime in seconds.
- The closure runs only on a miss.
- count() hits the database on that miss.
- Later calls return the integer from cache.
- forget deletes the key after a publish.
- The next call recomputes.
- Do not cache a user-specific page under a global key.
Common Pitfalls & Security
Watch the failure mode, not only the happy path.
- A global key that includes one user's drafts leaks those drafts to everyone.
- remember forever without forget serves a stale catalog.
- Caching the Eloquent models themselves can blow the cache store. Cache the integer.
- A cache outage should fall through to the query, not take the homepage down.
Best Practices & Modern Standards
Cache derived numbers and fragments, with a short TTL and an explicit forget on write.
Name keys after the data, not after the page URL alone.
Real-World Use
The homepage shows how many lessons are published. The number is cached for five minutes and cleared when an instructor publishes.
Frequently Asked Questions
What does 300 mean?
Seconds. Five minutes.
When does the closure run?
When the key is missing or expired.
How do I clear one key?
Cache::forget with the same name.
Can I cache a collection of models?
You can, but a count or a small array is safer. Large model graphs get stale and heavy.