Laravel Validation: Keeping Stock and Prices Updated During Checkout
Imagine a customer is halfway through completing their order form, and suddenly, the price of an item they're purchasing shifts, or worse, the item sells out. Obviously, you can't let them check out with outdated information. So, how do we ensure everything is up-to-date at the point of submission? Today, I'm going to walk you through two strategies to achieve this: the standard Laravel approach and a more dynamic, user-friendly method using Livewire.
Consider the error messages that pop up: this is our goal. We want to flag up-to-date issues right after the order is placed. For instance, maybe the price of the first item went up, or the second item sold out and isn't available in the required quantity anymore.
Handling this scenario isn't straightforward because Laravel doesn't provide a built-in validation rule for this specific case. So, we'll need to craft a Custom Validation 00Rule. But before we dive into that, let's set up our basic project structure.
Setting Up a Simple Product Ordering System in Laravel
Firstly, we need to consider our database. For this example, all we require is a single table named "products."
Moving forward, I've put together a basic demo project. It's constructed using our straightforward Laravel Breeze layout, with two essential routes and a single controller to handle orders.
Here's how the routing is set up in our routes/web.php
file: