In this episode, we dig into one of those sneaky performance issues that often happens: making lots of duplicate database queries when reading cart data multiple times on the same page. We use Laravel Debug Bar to check out the extra queries and then intentionally simulate a situation where the cart data is accessed several times.
After duplicating our cart code a few times, it's obvious we're re-fetching the cart from the database over and over, which is super inefficient. To fix this, we don't reach for an external cache like Redis; instead, we cache the cart inside our class by storing it as a property. Because our cart service is a singleton in the service provider, this works perfectly.
With just a few lines of code, we make sure the cart model is only loaded from the database once per request, no matter how many times we call it. We double check with Debug Bar that duplicate queries are gone, and everything looks much better. We wrap up by cleaning up our navigation markup and confirming this is an easy win for performance!