Categories: Development

Using Laravel cache to set, get and forget data

Using Laravel cache to store data in a cache, get the cache and then forget the data cache.

Laravel makes caching extremely easy and should be implemented if you are seeing the existence of sluggishness.

By using cache you can rapidly speed up your application and save on resources by not continuously doing database queries or calculations on the backend.

As default Laravel cache will use the file driver.

Storing cache

There are two main ways to store data into the cache, the first being put:

$users = Users::all();
Cache::put('all_users', $users);

Here the Users data gets stored as the all_users key in the cache. You can also pass an extra parameter for the expiry time in minutes for the cache.

The next method is with using remember:

$users = Cache::remember('all_users', 60, function () {
                return Users::all();
            });

Remember is a retrieve BUT also store if not exists function. So if the all_users cache didn’t exist or it was expired (60 minutes / 1 hour set above) it would refresh it with the Users::all() data.

Using add means the cache will only be stored if that key is not already present in the cache.

Cache::add('all_users', $users);

If using the file cache driver the cache files will be stored at storage/framework/cache.

 

Getting from the cache

Fetching items from Laravel cache can be done with get you just need to define its cache key:

$users = Cache::get('all_users');

You can check if the cache key exists, else get() will return null

if (Cache::has('all_users')) {
  //Has cache
} else {
  //No cache found
}

As shown above, the remember() function is also used to fetch cache however it will only return the cache if it exists.

Alternatively, you can get the cache data and then delete the cache in one command with pull

$users = Cache::pull('all_users');

 

Forgetting the cache

Destroying or wiping an item from the cache is done with forget

Cache::forget('all_users');

If you ever wanted to clear the whole cache:

Cache::flush();

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago