Laravel 10 -How to use Laravel's Caching Features to Improve Performance

Hello Artisan, today I'll show you how to implement caching features in our laravel application. Laravel provides several caching mechanisms that can be used to improve performance in web applications. Caching can help reduce the number of database queries and improve the overall response time of the application. So, let's see how we can use Laravel's caching features to improve performance of our application.

Table of Contents

  1. Setup Caching feature
  2. Available Methods for caching feature 

Setup Caching feature

At first we need to enable caching in our Laravel application. Laravel supports several caching drivers, such as file, database, redis, and memcached. To enable caching, we need to specify the cache driver in the .env file. Here is an example of how to enable caching using the file driver:

CACHE_DRIVER=file 

Caching Queries:

We can also cache our queries as well. Suppose any query which can be used in every page of our project. So, it's good to cache them. Let's see the below code snippet.

$users = Cache::remember('users', 60, function () {
    return DB::table('users')->get();
});   

In this example, the remember() method caches the query result for 60 seconds. The first argument is the cache key, which is used to retrieve the cached data. The second argument is the expiration time in seconds. The third argument is a closure that returns the query result.

Cache Tags:

Laravel's caching system also supports cache tags, which can be used to group related cache items together. This makes it easy to clear all cache items in a particular group. Here is an example of how to use cache tags:

Cache::tags(['users', 'admins'])->put('john', $user, 60);

In this example, the put method caches the $user object with the key john for 60 seconds, and adds the tags users and admins. This makes it easy to clear all cache items with the users or admins tag using the forgetTag method by below source code:

Cache::forgetTag('users');

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚