Laravel caching

What is caching? Why do I need it?

Caching is a technique to cache data for certain period of time. Caching is very useful skill if you are working on high traffic websites.

High traffic websites always doing heavy database lifting. To reduce load on database servers you need to cache the data which does not often change.

For example, if you have a blog website where you list the recent blogs. Your websites has millions of users accessing per day. You do not write blogs every minute so why can't we just cache the list of blogs that coming from the database for certain period of time.

If you cache the data for 5 minutes it saves the db queries for 5 minutes which can reduce an amount of hits to your database and can speed up your website loading as well.

Define cache driver in .env file

Laravel supports following types of caching drivers:

  • apc
  • file
  • redis
  • array
  • database
  • memcached

You can define settings for cache driver in .env file of laravel root project.

CACHE_DRIVER=file​

How does caching work?

Let's understand how caching work in general. Followings is a flow of caching:

  • Every cache is identified with a unique id called cache_key
  • Using this cache key we check to see if cache already exists
  • If data is not found for given cache key we generate the data and store it using cache key
  • Now, next time we check to see if data exists using cache key we find data
  • Stored data is stored for specified time and exerciseires after it passes that time

How to create/update cache in Laravel?

To create a cache in laravel you have to follow the steps below:

// let's take a basic example of how to use the cache in real
// let's define a unique cache key to store user list
$cache_key = 'user-list-key';

// define cache time and
// cache unique key for users
$time_in_minutes = 5 * 60; // 5min

// first try to get the value from the cache if 
// data is not found using our $cache_key
// it will return null value for given $cache_key
$user_lists = Cache::get($cache_key);

// let's make sure if we do not found data
// we fetch the data from the model and store
// in a cache for next 5 minutes
if(!$user_lists) {
	
	// at this point we do not have data
	// let's fetch it from the user model
	$user_lists = DB::table('users')->get();

	// let's store this new list with our
	// specified cache key for 5 minutes
	Cache::put($cache_key, $user_lists, $time_in_minutes);
}

// check our data
dd($user_lists);

You can perform the above operation with much smaller code as well using remember function provided by laravel cache class.

// define cache time and
// cache unique key for users
$time_in_minutes = 5 * 60; // 5min

// let's take a basic example of how to use the cache in real
// let's define a unique cache key to store user list
$cache_key = 'user-list-key';

// remember function first checks to see if given key exists
// in the cache if not then it will run the function and add
// data to cache with supplied $cache_key as identifier
$users = Cache::remember($cache_key, $time_in_minutes, function () {
    return DB::table('users')->get();
});

// will print users array
dd($users);

There are other useful functions provided by laravel cache facade as seen below:

// pull the cache and delete the data from cache
// will return null if no cache_key found
$value = Cache::pull($cache_key);

// The add method will only add the item to 
// the cache if it does not already exist in cache
Cache::add($key, $value, $exerciseiration_time);

// Storing Items Forever 
Cache::forever($key, $value);

// Remove item from the cache
Cache::forget($key);

// Function to check to see
// If data exists for given cache key
Cache::has($cache_key)

// $key: will be the key used to store value
// $value: will be the data that we need to store
// $exerciseiration_time: will be the time until it caches that data
Cache::put($key, $value, $exerciseiration_time);

What is cache tagging in Laravel?

Laravel helps you easily categorize your cache so that you can easily flush/delete them later.

For example: if your website caching user data and later you want to delete cache data for your users you might have to go through each user and delete the cache for them one by one.

However, if you tag your individual users under user tag then later on you can just flush the user tag and all the users under users tag will automatically be flushed or deleted.

To create a tagging follow the code below:

// adding John and Doe to same user group or tag
Cache::tags(['users'])->put('John', $john, $exerciseiration_time);
Cache::tags(['users'])->put('Doe', $doe, $exerciseiration_time);

// later when we decide to remove all users from the cache
// we will use following function so that we don't miss to
// delete John or Doe or any other users added to same tag
Cache::tags(['users'])->flush();

To learn more about caching and their driver follow the official docs provided below:

Laravel Caching