Create a simple cache with Redis using Laravel

Arsy Opraza
UNIKOM Codelabs
Published in
2 min readFeb 3, 2022

In this post, I will share how to create a simple cache with Redis using Laravel.

What is Cache?

Cache is a high-speed data storage layer that stores a subset of data, typically for temporary use. Caching allows you to reduce load time for your application because your first request for data will be stored in fast access hardware such as RAM and the second time your request for data is not by primary storage location (Server or Database) it's from Cache. Caching allows you to efficiently reuse previously retrieved data or computed data.

So, the benefit of cache is improved application performance, reduced database cost, and reduced Backend load on your database.

Cache can be implemented in Client-Side or Server-Side, at this moment we implement in Server-Side with Redis.

And what is Redis?

Redis, which stands for Remote Dictionary Service is an open-source in-memory data structure store, used as a database, cache, message broker, and queue. Redis provides data structures such as strings, hashes, lists, and sets. (see here a list of data structures support for Redis).

Basic Concept of Cache with Redis

source

In first-time users request data or resources to your server, the server can check, if data is not stored at Redis, server query data from Database and save it to Redis. And the second time the user requests the same data, the server will load from Redis which is save your time and make an application can faster than before, and save cost from load data from the database.

Installing Predis on Laravel

Predis is a package for interacting with Redis client for PHP, we will install via composer:

composer require predis/predis

Configuration Redis

Open your .env file and config like this (adjust it with your Redis config):

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_CLIENT=redis
REDIS_CACHE_DB=0
CACHE_DRIVER = redis

Then, check your Redis connection:

127.0.0.1:6379> ping
PONG
127.0.0.1:6379>

Create new route

Assume we have a user controller, then you should add routes like this:

Route::get(“/list_with_cache”, “UserController@getListUserCache”);Route::get(“/list_with_query”, “UserController@getListUserQuery”);

That route is used to get data from cache and database.

List User from Cache

Open your UserController and write a method for getting data from cache:

First, we check if data is available or not in Redis with key list_user_redis_
and then return JSON at the first time, and the second time you will get data from Redis.

Testing

If we run the program it will return like this

--

--