Laravel Cache

How to Integrate Laravel Caching to improve App Performance?

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.

Read More: Laravel Blade template cheat sheet

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

Prerequisites


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


I recommend you install the Laravel apps on Digitalocean Hosting or Cloudways managed hosting platform so you will not face any server-level problems. Because it is simple to host Laravel applications in a few easy steps but also handles server-level difficulties.

Cached Laravel


An effective and efficient API is available in the 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. You can define the default value you want to be returned if the item is not found by passing a second parameter.

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 the storage timein the put method:

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

Removing Items From The Cache

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

Cache::forget('key');

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

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

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

Cache::flush();

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');

Add comment