In this episode, we work on building the cart summary for our shopping cart, which gives users a running total of all items in their cart, taking quantities into account. We start by ensuring that when we loop through the cart items, they're properly keyed (using the variation id) so that Reactivity works smoothly, and items don't jump around in the UI when their order changes.
Next, we jump into some backend code tweaks: we explicitly order the cart variations by their IDs when retrieving them from Laravel, so they stay in a predictable order.
Then the main focus is creating the subtotal calculation. We add a summary section in our cart markup, showing the subtotal and a checkout button. To get the subtotal, we add a formattedSubtotal
method to our Cart model—which uses another subtotal
method under the hood. This function goes over each cart item, multiplies the item price by its quantity, and totals it all up using Laravel's reduce
collection method. We walk through a clear example so you understand how the subtotal gets calculated for multiple different items and quantities.
On the UI side, we create a new custom "button anchor" component that acts as a checkout link, looking like a button but behaving like an anchor tag, complete with sensible default behaviors and styling. We quickly test and confirm that our subtotal displays correctly and that the checkout button points to the expected place (even though it's a placeholder route for now).
By the end, we've got a functional, reactive cart summary with real subtotal calculations and a customizable checkout button, making the shopping experience much more polished!