Implementing Advanced Redis Caching in Laravel 11

Websolutionstuff | Oct-21-2024 | Categories : Laravel

In this guide, I’ll walk you through implementing advanced service-level caching in Laravel 11 using Redis. Caching is essential for improving the performance of your application, but beyond basic caching, we can use more advanced techniques such as selective data caching, cache tagging, and complex strategies to optimize performance further.

Let's explore how you can use Redis in Laravel 11 to take your caching strategy to the next level.

Prerequisites

  • Laravel 11 installed
  • Redis installed and running
  • Redis driver configured in your cache.php file

Implementing Advanced Redis Caching in Laravel 11

Implementing Advanced Redis Caching in Laravel 11

 

Step 1: Configure Redis in Laravel

First, ensure Redis is set up as the default caching driver in your Laravel application. In the cache.php file, set Redis as the default driver.

'stores' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
    ],
],

Make sure Redis is also configured in your database.php file:

'redis' => [
    'client' => env('REDIS_CLIENT', 'phpredis'),
    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', '6379'),
        'database' => env('REDIS_DB', '0'),
    ],
],

 

Step 2: Basic Caching in Laravel

Before diving into advanced strategies, let's review basic caching. You can cache any data like this:

use Illuminate\Support\Facades\Cache;

$users = Cache::remember('users', 60, function () {
    return User::all();
});

This caches the list of users for 60 minutes. Now, let's move on to more complex scenarios.

 

Step 3: Selective Data Caching

Selective caching allows you to cache only specific portions of your data. Suppose you have a large dataset, but you only want to cache a filtered subset:

$activeUsers = Cache::remember('active_users', 60, function () {
    return User::where('status', 'active')->get();
});

By caching only the active users, you avoid unnecessary caching of large amounts of data, keeping your cache lean.

 

Step 4: Using Cache Tags for More Flexibility

Cache tagging allows you to group related cached items, making it easier to clear or manage caches that belong to the same group. This is useful when you want to cache different pieces of data and invalidate them together.

use Illuminate\Support\Facades\Cache;

// Cache data with tags
Cache::tags(['users', 'posts'])->put('latest_posts', $posts, 60);

// Retrieve data by tags
$posts = Cache::tags(['users', 'posts'])->get('latest_posts');

// Clear all caches with the same tag
Cache::tags(['users'])->flush();

In this example, we're tagging the cache with users and posts. This allows you to clear all caches associated with users without touching other cached data.

 

Step 5: Complex Cache Strategies with Cache Dependencies

You may want to cache complex relationships between data. For example, caching a list of products that depends on categories. If the category changes, the product cache should be invalidated as well. You can achieve this using a combination of cache tagging and cache invalidation strategies.

use Illuminate\Support\Facades\Cache;

// Cache products based on category
$products = Cache::tags(['category', 'products'])->remember('category_1_products', 60, function () {
    return Product::where('category_id', 1)->get();
});

// If the category is updated, clear the related product cache
Category::find(1)->update(['name' => 'New Category Name']);
Cache::tags(['category'])->flush(); // This clears all product caches under the category tag.

This strategy ensures that whenever a category is updated, the corresponding cached products are also invalidated, maintaining cache consistency.

 

Step 6: Cache Busting with Event Listeners

For a more dynamic approach, you can set up event listeners to automatically clear or update caches when specific events occur in your application.

In your AppServiceProvider.php, listen for model changes.

use App\CategoryUpdated;
use App\Listeners\ClearCategoryCache;
use Illuminate\Support\Facades\Event;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Event::listen(
        CategoryUpdated::class,
        ClearCategoryCache::class,
    );
}

Then, in your listener, clear the relevant caches:

use Illuminate\Support\Facades\Cache;

class ClearCategoryCache
{
    public function handle(CategoryUpdated $event)
    {
        Cache::tags(['category'])->flush(); // Clear category cache on update
    }
}

This automatically clears the cache whenever a category is updated, ensuring that cached data stays fresh.

 


You might also like:

Recommended Post
Featured Post
How To Use OpenAI In Laravel 8/9
How To Use OpenAI In Laravel 8...

In this article, we will explore the integration of OpenAI into Laravel versions 8, 9, and 10. Our focus will be on unde...

Read More

Feb-06-2023

How To Create Calendar Event In Laravel 9 Using AJAX
How To Create Calendar Event I...

In this article, we will see how to create a calendar event in laravel 9 using ajax. Here, we will learn how to add...

Read More

Dec-28-2022

How To Send Email Using Markdown Mailable Laravel 9
How To Send Email Using Markdo...

In this article, we will see how to send email using markdown mailable laravel 9. we will learn laravel 9 to s...

Read More

Aug-05-2022

Laravel 8 Image Upload Validation
Laravel 8 Image Upload Validat...

In tutorial we will see how to validate laravel 8 image upload validation. In laravel 7/8 you can validate image using t...

Read More

Dec-15-2021