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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago