"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The new Cache::flexible() of Laravel

The new Cache::flexible() of Laravel

Published on 2024-11-08
Browse:253

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/

Release Statement This article is reproduced at: https://dev.to/kachkolasa/the-new-cacheflexible-of-laravel-265k?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3