In this episode, we're diving into Laravel's new cache()->flexible()
method and exploring how it can make your app both faster and smarter when it comes to caching.
We start by quickly reviewing basic caching in Laravel: grabbing a batch of users from the database and using the cache()->remember()
function to store them. To better see what's going on under the hood, we install Laravel DebugBar to track our database queries and verify when the cache is being hit versus when a fresh database call is made.
Next, we introduce the star of the show: the new flexible caching method. This uses the "stale-while-revalidate" pattern. In a nutshell, you set two time periods: a "fresh" period where cached data is served instantly, and a "stale" period where cached data can still be served, but Laravel will revalidate (refresh) it in the background. This clever system means users keep getting speedy responses, even if the data is a tad bit old, while fresh data is fetched behind the scenes without making users wait.
We then see this in action: tweaking refresh and stale intervals, inspecting when queries are executed, and seeing how the user experience stays smooth. Finally, you'll learn about the trade-offs involved and get encouraged to experiment with these values to fit your app's needs.
Bottom line: if you want to make your Laravel apps snappier without giving up too much on data freshness, this episode is a must-watch!