@devio Well, you need to model inventory movements, and decide when inventory is reserved:
- When a customer adds an item to their cart?
- When a customer begins checkout?
- When a customer successfully completes payment for an order?
Unfortunately there is no one single answer; which one you choose very much depends on what fits best for your business use case. But no matter which one you choose, you’re going to need to lock rows to prevent individual items being held by multiple people.
For example, if two people open a page for a product and it says there is one left in stock, and then your code just does something like…
$product->inventory()->update([
'in_stock' => $product->in_stock - 1,
]);
…you may end up in a situation where you end up with a negative stock level after both requests update the inventory for the product.
You also need to account for reversals of stock adjustments. So if you say, reserve stock when a customer adds it to their cart, you need to ensure you put that stock “back” if the cart expires. For example, if you delete carts older than 2 days, you might have some code that does…
Cart::query()->where('updated_at', '<', Date::now()->subDays(2))->delete();
…while that will delete any stale carts, your stock level is not going to magically replenish; you need some code that will replenish your inventory with the same quantity that was held in those carts you’re purging.