Laravel Cache

How to Integrate Laravel Caching to improve App Performance?

0 / 0 5 Mins Admin

October 31, 2022


Laravel Caching is essential for enhancing the performance of your web apps because it speeds up the website and decreases load times. Therefore, use the Laravel caching features, which worked wonders for the project, to resolve the performance issue.

I’ll show you how to use several caching techniques in Laravel in this tutorial.


I’m assuming that you already have a Laravel application running on a web server for the sake of this tutorial. As for my setup:

  • PHP 7.4
  • Laravel 7
  • MySQL

Cached Laravel

An effective and efficient API is available in Laravel for a variety of caching backends. The config/cache.php folder contains the Laravel cache configuration.

You can define which cache driver to use by default with this file.

Popular Laravel caching backends include:

  • Memcached
  • Redis
  • Database
  • File
  • Array

You can modify the CACHE_DRIVER=file in the .env file.

How to use Laravel Cache?

You can use the Cache facade, which is what we’ll be using in this guide, to get a cache store instance.

use Illuminate\Support\Facades\Cache;

Cache Retrieve

The Cache::get('key'); method can be used to obtain data that has been stored previously. If the item does not exist in the cache, null will be returned. By passing a second parameter, you can define the default value you want to be returned if the item is not found.

public function index()
  $value = Cache::get('key');
  // or with default value
  $value = Cache::get('key', 'default');

Check for item existence

To find out if something is in the cache, use the has method.

if (Cache::has('key')) {

Storing Items In The Cache

To put items in the cache, use the put method on the Cache facade:

Cache::put('key', 'value', $seconds = 10);
// OR
Cache::put('key', 'value', now()->addMinutes(10));

The item will be available in the storage forever if you omit the storage time in the put method:

Cache::put('key', 'value');

Removing Items From The Cache

Using the forget method, you can eliminate items from the cache:


Additionally, you can remove items by entering a negative or zero integer for the expiration:

Cache::put('key', 'value', 0);
Cache::put('key', 'value', -5);

Using the flush technique, you can completely clear the cache:


The Cache Helper Method – Access Cache Globally

You can get information via the cache using the global cache function.

The cache function will return the value of the supplied key when it is invoked with a single, string argument:

$value = cache('key');