The new Cache::flexible() of Laravel

Waiting for large dataset to compute every time you hit a route sucks! And users don’t want to wait, everyone has short retention these days, so we fixed it years ago by using Cache. Laravel has a Cache Fascad to help us caching data, and we have been using the Cache::remember() which is a great method to cache some data for a period of time until they are expired.

But in a recent event, Laravel announced the new upcoming feature in the Cache Fascad called “flexible”. It uses the new defer() function of laravel in the background.

How Cache::flexible() works

Cache::flexible() is very similar to Cache::remember() which we are already familiar with and has a very few changes in the codes but a huge impact on the performance. You provide two values for time instead of 1 unlike Cache::remember().
If you are passing, 5 and 10 as the time frame for Cache::flexible() then when a user first hit or visit the route, the user must wait for the values to be cached and when keeping hitting the route within the 5 seconds then it just returns the cached values same as Cache::remember(). But here’s the interesting part, if a user hit the route within 5 to 10 seconds time frame (as we provided) then Laravel will still provides the cached values for the firs visit within that timeframe and starts a background worker to cache the values again. And when the user visits the route again, he gets refresh data but this time without waiting for the data to be cached or computed unlike Cache::remember().

This can be tricky to understand for some of you, I recommend to read this article I wrote about it in more dept and with real life examples: https://laraveleco.com/cache-flexible-method-of-laravel/

Please follow and like us:
Pin Share