Laravel – Cache

Sometimes in applications, there’s a need to speed up response time. One possible way to do that is to use a cache. Cache can store data for which the load time is too long. Data saved in the cache needs to be rarely changed; otherwise, the cache becomes pointless.

Cache drivers

Laravel offers internal and external caching solutions. Internal solutions like arrays, files, or introduced in Laravel 11 database cache driver. External solutions that work out of the box are Memcached, Redis or DynamoDB. These solutions offer the possibility to cache any data that the programmer wishes. Most likely, it will be used to cache heavy database queries with a long execution time. But nothing stops you from storing any other data in the cache.

Cache Facade

Laravel offers a Cache Facade which supports all default drivers. These are some basic functions to operate on a cache:

//Determine if value assigned to key exists
Cache::has('key');


//Get value assigned to passed key
Cache::get('key');


//Store new value in cache
Cache::remember('products', $seconds, function () {
   return Product::all();
});


//Retrieve and delete value assigned to key
Cache::pull('key');


//Delete value assigned to key
Cache::forget('key');

Cache Facade allows you to operate on multiple cache drivers.

//Get value from redis cache
Cache::store('redis')->get('key');


//Get different value from database cache
Cache::store('database')->get('key');