Caching in Laravel with Redis: Simple Example

Tutorial last revisioned on March 17, 2024 with Laravel 11

Caching with Redis is one of the common requirements in Laravel job descriptions. But it's not complicated it all, this tutorial will show you the fundamentals.

Here's a simple tutorial 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

Predis is a flexible and feature-complete Redis client for PHP. Install it via Composer:

composer require predis/predis

4. Configure Redis in Laravel

Change the CACHE_STORE to redis in the .env file:

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

5.1 Cache an Eloquent Query

Suppose you have an Eloquent query like this:

$users = User::where('active', 1)->get();

To cache this query result with Redis:

use Illuminate\Support\Facades\Cache;
 
$users = Cache::remember('active_users', 60, function () {
return User::where('active', 1)->get();
});

Here, 'active_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.

5.2 Clear Cache

To clear the cached result:

use Illuminate\Support\Facades\Cache;
 
Cache::forget('active_users');

6. Display Cached Data

Here's a simple example to display active users using caching:

  1. Create a route in web.php:
use Illuminate\Support\Facades\Cache;
use App\Models\User;
 
Route::get('/active-users', function () {
$users = Cache::remember('active_users', 60, function () {
return User::where('active', 1)->get();
});
 
return view('active_users', ['users' => $users]);
});
  1. Create a view active_users.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Active Users</title>
</head>
<body>
<h1>Active Users</h1>
<ul>
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
</body>
</html>

Now, when you visit /active-users in your browser, it will fetch and display active users from the database and cache the result for 60 seconds.


7. Check Current Cache

If you want to see what values are cached at the moment, you can do it with a tool called RedisInsight.


You can read much more about Redis in our premium tutorial Redis in Laravel 101: Main Things You Need to Know.

avatar

Just a quick correction for the Cache::remember call. "60 is the number of minutes" is not true. It's the number of seconds to cache.

See: https://laravel.com/docs/10.x/cache#retrieve-store

avatar

Thanks. Updated article

avatar

It has a minor typo. 60 is the number of seconds.

avatar

Here, 'active_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, when you visit /active-users in your browser, it will fetch and display active users from the database and cache the result for 60 minutes.

Those 2 paragraphs are conflicting, kindly correct them. Otherwise thanks for tips always

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1056 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials