Thursday, June 23, 2016

How to Cache Database Queries in Laravel? | Improve site loading speed using caching

cache database with redis

In this session I'm gonna discuss about how you can Cache Database Queries with Redis. First of all you may have asked why Caching Database is needed? The main reason is it's reduce the site loading speed. So while you have low bandwidth also you can easily access the site. It reduces the No of  hits in the database, means it won't load the Queries every time from database. So your database will be more secure and site will be optimized. So let's not waste our time and start the session:

1. First of all , install Laravel Debugbar package in our project.



As you see by this debugger you can see No of controllers in that page, No of Queries, No of views, site loading time etc. We'll use this debugger in this tutorial for getting the optimized time it'll take for loading the request.



2. Let's create a controller where we are going to caching the database:

public function userDetails()
  { 
        $user = Cache::remember('users', 5, function()   // cache for 5 minutes
           {
               return DB::table('users')->get();
           });        
       $student = Cache::remember('students', 5, function()
           {
               return DB::table('students')->get();
           }); 
       return view('userDetails',compact('user','student'));
    }

3. Now if we request in routes.php with the view page, in first load we'll see the view page like this:

before caching



As you see there are 2 Database Queries after first loading of the page. But when you going to do the second load you'll see the No of  Queries become 0 and also site loading times also reduced as it cache the database for 5 Minutes like this:



after caching



So That's it for today. Hope you like the tutorial and also implement in your recent project.
Thank you for being with me.










Related Articles

0 comments:

Post a Comment