What is a good way to keep track of cart quantity across different pages?
So I have a little cart icon in the upper right of my navbar which displays the number of items in the cart.
To get the quantity of items in the cart I currently have to hit the database and count the number of items in the cart. This happens every time the user clicks a button to navigate to a new page since the cart icon is in the navbar part of the UI.
I'm assuming there's a better way to do this so I don't have to hit the database every time? Is there something like a cookie in Laravel but server side? A little direction would be awesome.
@jlrdw Not if the user logs in/out, as the session is flushed.
@rotaercz Instead, you could create models for your cart and cart items, and then use a cookie to store the cart ID so you know which cart to pull from the database.
@martinbean Hey, thanks for the reply. Cart is a table in the database and I keep track of items based on the username. Though I can see scenarios where if the user didn't make an account that would be the way to go (via using a cookie to store the cart ID since they wouldn't have a username).
Basically I'd like to show the cart quantity in the upper right (similar to what Amazon does) without having to hit the database every time the user navigates to a new page. I don't have a lot of experience using sessions though it does sound like the right direction for what I'm trying to do.
You could also use the browser's LocalStorage to store the cart. You'd have to do a little fancy footwork if you wanted to allow people to come back to the site with a different device and see their cart though.
@imeda@ohffs Thanks for the replies. I definitely want to show the correct number on different devices too.
I'm thinking I can have a variable that stores the cart quantity. When the site first loads, I'd query the database for the correct initial value and after that variable is populated, I'd just update it whenever the user adds/removes items from their cart.
What are the pros and cons of cache, session, and localstorage relative to each other for this kind of thing?
I'm thinking of using sessions but need a little help. Since the navbar blade is used for all my pages, I'd have to add the session code to every single controller but that seems the wrong way to go about doing this. What's the right way to go about doing this/set this up?