Cache laravel query results using file driver for ajax

Often in your laravel application you are loading and fetching the results on the database which doesn’t necessarily needs to be fetched on every page reload. Query that takes longer amount to execute slows down the web application.

To overcome this, we can use Laravel Caching for the same.

Laravel provided many drivers for caching. Go through it on laravel cache.

In this demonstration, we will cache the query results which is being returned as an JSON response by the controller and is being utilised by an Ajax call.

Livewire Component Library

Default cache driver is specified in file cache.php like following

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

'default' => env('CACHE_DRIVER', 'file'),

Route for the Ajax URL is :

    Route::get('caching', 'Controller@getDetails'); 

Controller method where caching is done. Cache Facades is used for accessing all cache methods provided by Laravel:

use Illuminate\Support\Facades\Cache;
public function getDetails(Request $request) {
  if(Cache::get('key') == null)
        {
            $data = query;
            Cache::put('key',  $data  , now()->addMinutes(60));
        }
        $data = Cache::get('key');
        return $data;
}

We are checking whether data is not cached or not using Cache::get  method returning null.
If data is not cached already, run query to fetch data then use Cache::put() to cache the data with specified key for desired time.
Return the data in ajax call response using same Cache::get method.

Script for Ajax call is :


<script>
$(document).ready( function () {
	$.ajax({
                    url: "/caching", 
                    type: "GET",          
                    cache: true, 
                    success: function(response){
	console.log(response);
						})
                    }
					
				});
</script>

This is the brief on caching the data using Cache Facades provided by Laravel.

Site Footer