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.

Laravel PHP cacheAs 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


If you ever wanted to clear the whole cache: