Laravel Cache-Load your pages very fast

Hello Laradevs !

Our applications may have lots of routes that makes database query when ever we visit that route. Imagine we have thousands of visitors everyday, every time a visitor visits the route it makes database query. Database queries are itself bit time and memory consuming. As it needs to process multiple models and some times run N numbers of queries. To overcome this problem and load our Laravel application faster we use query caching.

Query Caching is a technique to Speed up page loading by storing the queried data in Cache Memory and remembering that. Once it is remembered and whenever exact same query need to perform, it simply returns data from the cache without performing any query and without processing any model and our page will load instantly.

Lets Consider we have a Post model and Post controller, inside post controller's index method we have are getting the all post with all its relations as below.

 public function index()
    {
        //get all the posts with category and user
        $post = Post::with('categoty', 'user')->get();
       
        return view('post.index', compact('post'));
    } 

In above example we are fetching all the post with its category and user. Even we are egger loading the relations, there will be only 3 queries but the number of model processed will multiplies. So here we which will lead to slow down our application. Using Cache there will be database query and model processing only on 1st reload after that there will be zero queries and zero model processed.

To store the query use use Illuminate\Support\Facades\Cache; at the top of your controller and modify the method as follows,

 public function index()
    {
        $post = Cache::rememberForever('all-posts', function () {
            return Post::with('categoty', 'user')->get();
        });
       
        return view('post.index', compact('post'));
    } 

Lets see with example:

Here we have 5000+ posts, 10 users and 100 categories in my local database for demonstration. I am using Laravel-Debugbar to analyze all the queries, Models, memory usage and response time.

Without caching the query response without Laravel Cache

Using Query Cache The result will show from 2nd time the route visits . response using Laravel cache

You can see the improvement on the response time has improved by more than 50% that's the beauty of Laravel Cache. And there are 0 query executed and 0 model processed and response time is around 400ms which is less than previous time.

Now what about when we add new post, as its not going to make any request in database again. We have to forget the old cache when ever we update, edit and delete something. for that we can use

Cache::forget('key'); 

remember the argument 'all-post' inside Cache::rememberForever() is the key. so to clear this the command will be as follows

Cache::forget('all-post') 

we can clear the entire cache using

Cache::flush(); 

lets see one example to clear the posts for updating an post

inside the update method

 public function update(Request $request, Post $post)
    {
        // Write update logic here....
        .....;
        .....;
        Cache::forget('all-post');
        Cache::forget('post-'.$post->id);  // If you are caching single post 
         								  // with key 'post-id'
        return .......;
    } 

You need to do this wile making any change on the post model like update create and destroy.

Conclusion

In this article I have explained all the basics and simplest way to use the default cache driver that is file cache. It that will help on improving site performance. You can read more about the Laravel Cache in the Laravel's Docs. For few data and models its not a big deal but for thousands of data and models it will be very slow and some time timeouts.

Hope this article help on improving your website performance. If you have any questions leave in the comment below. Thanks for reading.

Comments :