Home Backend Development PHP Tutorial Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching

Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching

Nov 12, 2024 am 09:29 AM

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:

  • Can quickly store and retrieve data
  • Supports various data structures like strings, lists, and hashes
  • Offers tools for managing cache expiration and clearing old data

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.

1. Setting Up Basic Caching with Laravel and Redis

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();
});
Copy after login
Copy after login

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.

2. Structuring Cache Keys and Expiration Times

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";
Copy after login
Copy after login

This key is clear, unique, and self-descriptive, making it easy to identify and manage within Redis.

3. Using Tags for Grouped Cache Management

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);
});
Copy after login

Now, if we want to clear all category-specific news caches (when news is updated), we can use:

Cache::tags(['news', 'category'])->flush();
Copy after login
  1. Caching Paginated and Filtered Data When adding pagination or filters (like category or tags), make each cache key unique to the parameters:
$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);
});
Copy after login

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();
});
Copy after login
Copy after login

This ensures each category and page combination has its own cache entry.

5. Automatic Cache Invalidation on Data Changes

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";
Copy after login
Copy after login

Now, whenever news is added or updated, all news and pagination tagged caches are flushed, keeping the data fresh.

6. Summary and Best Practices

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles