In this episode, we tackle the crucial step of reducing stock levels after a customer places an order. We start by iterating through the items in the order and, for each product variation, create a new stock record with a negative quantity to reflect the items that have just been purchased. While this initial approach involves running several queries (one for each order item), we mention that we'll revisit and optimize this later.
As we walk through the implementation, we run into a small hiccup — we need to make sure the amount
property is fillable in our Stock model. After adding that, we run the process again and verify that negative stock entries are being added correctly, matching the quantities ordered.
To tidy things up, we also implement a removeAll
(or clear
) method for the cart, clearing out all items once the order has been placed. We demonstrate how this works by confirming an order, checking the database, and ensuring the cart is emptied out.
By the end of this lesson, you'll have seen how to subtract ordered quantities from stock and how to clear the cart after checkout. We also show a quick reset and test the workflow from scratch to make sure everything’s working as expected.