Laravel 11: Caching With Redis

Sandeeppant
2 min readFeb 12, 2025

--

Caching plays a vital role in optimizing the performance of a web application.It can help reduce reads from the disk on your server, which is relatively slow in general.

Installing Cache engines such as Redis or Memcached to your VPS can help optimize your application’s performance relatively quickly.

Here’s a simple example on how to use Redis in Laravel for caching Eloquent queries.

1. Redis server: install/launch

Redis is not a Laravel-specific system, it is installed separately, just follow its official installation instructions.

Then, just launch it with the command redis-server.

2. Install Redis PHP Extension

Ensure you have the Redis PHP extension installed:

For Ubuntu based systems:

sudo apt-get install redis php8.1-redis

sudo systemctl restart php8.1-fpm.service

3. Install Predis Package

composer require predis/predis

4. Configure Redis in Laravel

Change the CACHE_STORE to redis in the .env file(In previous version their was CACHE_DRIVER).

CACHE_STORE=redis

Edit the .env file to change Redis server configuration if not using the default values:

REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

5. Use Redis in Laravel for Caching

Suppose you have an Eloquent query like this:

$users = User::whereNotNull('deleted_at')->get();

use redis to cache the query result like as shown below:

use Illuminate\Support\Facades\Cache;

$users = Cache::remember('deleted_users', 60, function () {
return User::whereNotNull('deleted_at')->get();
});

Here, deleted_users is the cache key, 60 is the number of seconds to cache the result, and the closure fetches the users when the cache is not found.

Now to remove the data from cache simply do the following:

use Illuminate\Support\Facades\Cache;

Cache::forget('deleted_users');

Thank you for reading. 🙋‍♂️

🏌️‍Follow me: https://medium.com/@sandeeppant

--

--

No responses yet