Laravel 8 Redis caching

Paul
2 min readNov 30, 2020

--

Redis is a key-value data store, and can be used with Laravel to cache data when you would otherwise need to load large amounts of data in real time.

Create a new laravel application

laravel new redis_sandboxcd redis_sandboxcomposer require predis/predis

Install redis if you haven’t already:

Linux: https://redis.io/topics/quickstart Mac: https://gist.github.com/tomysmile/1b8a321e7c58499ef9f9441b2faa0aa8 Windows: https://github.com/microsoftarchive/redis/releases/tag/win-3.0.504

We need to set the redis package to use predis as the default. In .env :

REDIS_CLIENT=predis

Or if you prefer you can modify directly in database/config.php:

'client' => env('REDIS_CLIENT', 'predis')

I like to set a prefix for to the redis keys, so that we can distinguish which messages came from this application. In the ‘options’ array in database.php:

'prefix' => env('REDIS_PREFIX', 'redis_sandbox_')

Now run the application:

php artisan serve

In web.php:

<?phpuse App\\Http\\Controllers\\CacheController;
use Illuminate\\Support\\Facades\\Route;
use Illuminate\\Support\\Facades\\Redis;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
$visits = Redis::incr('visits');
return $visits;
});

Any of the methods the Redis facade refers to statically are going to defer to the commands listed here through the redis-cli https://redis.io/commands.

The above command Redis::incr() refers to this redis-cli command https://redis.io/commands/incr and simply increments an integer by 1 each time. A possible use case could be number of visitors to a website.

If you now access the page at http://127.0.0.1:8000 (or wherever you are hosting the page), you should see a number beginning at 1 and incrementing each time you refresh the page. You can see that Redis persists the data.

Now if we switch over to the terminal and use the Redis command redis-cli you will now be able to query redis through the cli.

In this example we have created a key called ‘visits’ and prefixed with ‘redis_sandbox_’ in database.php.

This is basic Redis caching, I am planning on showing other things we can do with Laravel Redis. If you would be interested in that please leave a clap.

--

--

Paul
Paul

Written by Paul

I am a software developer and I like to write about interesting things I come across in my day to day.

No responses yet