Getting started with Redis on Lumen

You developing a RESTful API on Lumen or simply require a in-memory data storage/database for quick caching purposes. Let's talk about Redis.

Reading Time: 2 minutes

You developing a RESTful API on Lumen or simply require a in-memory data storage/database for quick caching purposes. Let’s talk about Redis.


As per the website;

“Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries.”

As per me; I’ve been using it for my own RESTful service and all I can tell you is that it’s fast and very simple to use – saving me lots of time in development. Furthermore, it’s easy on the resources.


Let us jump right into it.

Note: If you haven’t started working with Composer yet – this requires that. So go ahead Get Started with Composer first.


First off, Redis is a service that needs to be running to power your application. Head over to download and install it.

If you’re on Windows 10, I’d suggest using the Ubuntu Bash terminal that now comes along with it.

Read: Installing Ubuntu Bash terminal on Windows 10

Once Redis is up and running, head over to your Lumen project and require Redis. Lumen supports Redis so that makes it much easier for us.


Make sure you’ve uncommented $app->withFacades() in bootstrap/app.php.

  • composer require predis/predis (~1.0)
  • composer require illuminate/redis (5.2.*)
  • Register it in bootstrap/app.php by calling $app->register(Illuminate\Redis\RedisServiceProvider::class); in the file, under Register Service Providers.
  • As per the Lumen docs; If you have not called $app->withEloquent() in your bootstrap/app.php file, then you should call $app->configure('database'); in the bootstrap/app.php file to ensure the Redis database configuration is properly loaded.
  • Make sure your .env Lumen config file has this set CACHE_DRIVER=redis. (If you have .env.example instead; rename it to .env)

And that’s it! Hit the RedisPHP docs for all the commands.


To use it in Lumen, you can call it these ways

  • app('redis') (recommended)
  • $app['redis']
  • $this->app['redis']


The reason I recommend app('redis') is because it can be called anywhere, including closures and so on.



Basic Usage

Checking if a Key exists: app('redis')->exists($key)

Setting a key/value: app('redis')->set($key, $value)

Getting a value by key: app('redis')->get($key)

Setting an expiry for the key: app('redis')->expire($key, $seconds)


And you’re good to go!


If you’re wondering what REST API I was talking about, It’s Jikan; an unofficial API platform that handles over 5,000 requests daily!