Home > Article > Backend Development > Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching
Laravel and Redis are a powerful combination for boosting application speed and performance. Redis, an in-memory key-value store, is perfect for caching, especially when you need fast and frequent data access. In this guide, we'll look at effective caching strategies in Laravel with Redis. We'll cover how to cache data, manage expiration times, and efficiently clear caches.
Why Use Redis Caching?
When you cache with Redis in Laravel, you're essentially saving data temporarily to reduce the time spent querying the database. Caching speeds up data retrieval, reduces server load, and improves user experience by making pages load faster.
Redis is ideal for caching because it:
Let's explore how to best use Redis caching in Laravel.
Let's say we have a News Paper Site. Now we need to build Api to Get News.
To start, let's cache a simple API response, like a list of the latest news articles.
$data = Cache::remember('latest_news', 3600, function () { return News::latest()->get(); });
In this example:
Cache::remember stores data with a key (latest_news) and a time-to-live (TTL) of 3600 seconds (1 hour).
If a request for latest_news comes in again within the hour, Redis serves the cached data without querying the database.
To keep the data fresh without overloading Redis:
Set shorter TTLs for frequently updated data (e.g., 15–30 minutes).
Use longer TTLs (e.g., 1–2 hours) for data that rarely changes.
Use specific, structured cache keys that reflect the data content. For example:
$cacheKey = "news:category:category_1";
This key is clear, unique, and self-descriptive, making it easy to identify and manage within Redis.
Redis supports tags, which let us manage grouped data under a common tag. For example, tagging all news-related caches with news:
Cache::tags(['news', 'category'])->remember('category_news_1', 3600, function () { return $this->news_repository->getNewsByCategory(1); });
Now, if we want to clear all category-specific news caches (when news is updated), we can use:
Cache::tags(['news', 'category'])->flush();
$page = request()->input('page', 1); $limit = request()->input('limit', 10); $cacheKey = "news:page_{$page}:limit_{$limit}"; $newsData = Cache::remember($cacheKey, 3600, function () use ($page, $limit) { return News::latest()->paginate($limit, ['*'], 'page', $page); });
This way:
A unique cache entry is created for each page and limit.
Users can fetch pages quickly without re-querying the database.
For filtered data, include the filter parameters in the key:
$data = Cache::remember('latest_news', 3600, function () { return News::latest()->get(); });
This ensures each category and page combination has its own cache entry.
Clearing or "invalidating" caches ensures users see updated data when necessary. Here's how to automate it:
Use model observers for events like created, updated, or deleted to clear related caches.
Example observer for news:
$cacheKey = "news:category:category_1";
Now, whenever news is added or updated, all news and pagination tagged caches are flushed, keeping the data fresh.
To make caching work effectively:
Unique Keys: Structure keys with parameters like category, page, and limit.
Tags for Grouped Data: Use tags to easily manage caches for specific data groups.
Automate Invalidation: Set up observers to clear outdated caches on data changes.
Set Sensible Expiration: Choose TTLs based on how often the data changes, typically between 15 minutes and 1 hour.
Using Redis with this structured approach makes Laravel APIs respond faster, improves server load management, and ensures a reliable, efficient cache strategy that's easy to manage.
The above is the detailed content of Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching. For more information, please follow other related articles on the PHP Chinese website!