How To Use Laravel Cache For Quick Load Time

In this tutorial we're going to look at the basic usage of the Laravel cache. The use of Laravel cache , its makes our site more faster than only use of query builder. In this tutorial we will see how we can implement laravel cache mechanism in our application. 

Laravel provides an expressive, unified API for various caching backends. The cache configuration is located at config/cache.php. In this file you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like Memcached and Redis out of the box.

By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver.

As this is our testing purpose , so i use file cache driver. You can read laravel documentation for cache from this link cache in laravel cache best practices

 

Step 1: Add dummy data

Now open your command line interface and paste this command to your command prompt.

1. php artisan tinker
2. factory(\App\User::class,15000)->create()
3. exit

 

Read also : Advance Usage of Cache in Laravel

 

Step 2: Create Users.php class

Create a class name Users.php class inside the following directory and paste this following code.

app\Repository\Users.php

namespace App\Repository;
use Carbon\Carbon;

class Users {
   
   CONST CACHE_KEY = 'users';

   public function all($orderBy)
   {   

       $cacheKey = $this->getCacheKey();

       $users = cache()->remember($cacheKey, Carbon::now()->addMinutes(5), function () use($orderBy){

        return \App\User::orderBy($orderBy)->get();

       });

       return $users;
 
   }

   public function getCacheKey()
   {
       return self::CACHE_KEY;
   }

}

 

Step 3: Setup route

Now we are just checking our retrieving data for laravel cache. So i don't use any controller. if you want you can use controller to do it. 

routes/web.php

use Facades\App\Repository\Users;

Route::get('users', function(){

    return Users::all('name');

});

 

Now just visit this following url 

127.0.0.1:8000/users

Then you should see those below data which is coming from our cache driver. 

laravel-cache-example

 

This data is coming from cache, how you could be sure?  Ok, just see the following code.

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {

    return Cache::get('users');

});

 

Now visit this following url, you will see the same output. 

 

127.0.0.1:8000/cache

 

Hope you will love this tutorial. if you have any query, feel free to comment and don't forget to share. 

 

#laravel #cache #caching #cache-laravel