Caching Eloquent query with Redis in Laravel

Caching is a component that stores the data to serve future requests faster. Basically, cache store the data which you were serving earlier from the database. Why we need cache is let's assume we have a page which is serving the content from multiple tables, On each request, it will hit the multiple tables to serve a page. So, rather doing this if we implement the cache, it will make a copy of that multiple tables and serve the request without hitting the database.

By default, Laravel ships with multiple cache drivers.

  1. Redis
  2. File
  3. Memcached

In this tutorial, we will be using Redis with Laravel Eloquent for caching the data and see how cache works in Laravel and.

Also, I am assuming you have already installed the Redis and Laravel in your machine. If not, the below tutorial will guide you to the installation of Redis in Ubuntu step by step.

Easy steps to install Redis on Ubuntu 16.04 and 18.04

Install and configure Laravel 7 on Ubuntu 16.04 and 18.04

1. Config the Redis in Laravel

In this step, Add the Redis configuration in the Laravel .env file and set the default cache driver to Redis.

CACHE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Redis stores in-memory key-value in the database. Below is the example of Redis in Laravel.

Cache::put($key, $value, $ttl);

Below is the example:

Cache::put('randomKey', 'somevalue', 1800);

randomKey is the key and store the value somevalue and will expire in 30 Minutes. Below is code to get the value from the cache with key in Laravel

$var = Cache::get('somevalue');

2. Implementing Redis Cache on Laravel eloquent model

Now let's assume we have a table post and category and we want to fetch the details of the post with category details. Below are the examples without cache. The query would look like this.

public function getPosts()
{
	$allPosts = Post::with('categories')->all();

	return view('blog.article', compact('allPosts'));
}

Below is the example of how to set and get the data from the cache

public function getPosts()
{
	$key = __CLASS__.__FUNCTION__.'all-posts';
	$allPosts = Cache::remember($key, 1800, function() {
		return Post::with('categories')->all();
	})

	return view('blog.article', compact('allPosts'));
}

The above code will check if the key data is available in Cache. If not, it will fetch the data from the database and save it to the cache and
serve until the cache expires (which is 30 minutes)

Note: If you create, update the data in the database. It will reflect after the cache expires. To escape from this, you can flush the cache while creating, updating the data with the help of a key.