Boost Performance with Laravel's Memo Cache Driver

Need to reduce cache hits during request execution? Laravel's memo cache driver provides an in-memory layer that temporarily stores resolved cache values, significantly improving performance.
When dealing with expensive operations or frequently accessed cache keys within a single request, repeated cache lookups can become a performance bottleneck. Laravel's memo cache driver solves this by storing cache values in memory after the first retrieval, eliminating redundant cache store hits.
Let's see how it works:
use Illuminate\Support\Facades\Cache;
// First call hits the cache store
$value = Cache::memo()->get('key');
// Subsequent calls return from memory
$value = Cache::memo()->get('key'); // No cache hit!
// You can specify a cache store
$value = Cache::memo('redis')->get('key');
Real-World Example
Here's how you might use the memo cache in a data processing service:
class ReportGenerator
{
public function generateUserReport($userId)
{
// These will be memoized during the request
$userStats = Cache::memo()->remember("user-stats:{$userId}", 3600, function() use ($userId) {
return $this->calculateUserStats($userId);
});
$companyData = Cache::memo()->remember("company-data", 1800, function() {
return $this->getCompanyMetrics();
});
// Even if called multiple times in the same request,
// these won't hit the cache store again
$preferences = Cache::memo()->get("user-preferences:{$userId}");
return [
'stats' => $userStats,
'company' => $companyData,
'preferences' => $preferences
];
}
public function updateUserPreference($userId, $key, $value)
{
// This will forget the memoized value and write to cache
Cache::memo()->put("user-preferences:{$userId}", [
$key => $value
]);
// Next get() will hit the underlying cache again
$updated = Cache::memo()->get("user-preferences:{$userId}");
}
}
The memo cache driver intelligently manages its in-memory storage. When you modify cache values using methods like put()
, increment()
, or remember()
, it automatically forgets the memoized value and ensures data consistency.
Think of it as a smart cache layer that remembers what you've already looked up during a request, preventing unnecessary trips to your cache store while maintaining data accuracy.
Stay Updated with More Laravel Tips
Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:
- Follow us on Twitter @harrisrafto
- Join us on Bluesky @harrisrafto.eu
- Subscribe to our YouTube channel harrisrafto