In this episode, we're shifting focus from files and diving into how to validate the product data and actually store products in the database. First up, we clean out some dummy products we made earlier to keep things tidy. Then, we set up validation rules for all of our product form fields using Livewire's handy rules array and the validate
method. You'll see how to specify sensible validation rules like required
, max
, unique:products,slug
, and more for each input.
We also update our form to make sure error messages show up next to the right fields, matching the state object structure. Once all the rules are in place, we try submitting some test products and see validation errors in action if the inputs aren't quite right.
The episode goes a step further by actually creating a product in the database. We use the authenticated user's relationship to create the product using the validated array of inputs. But we soon hit a snag: price validation! The price field is being input as a decimal, but our database expects an integer (since we're storing in cents). To fix this, we use a Laravel Eloquent attribute mutator on the model that automatically multiplies price values by 100 when storing them. This ensures the data gets saved in the correct format every time.
After wiring up the mutator, we try out product creation again and see everything works as expected—the product shows up on the user's product page and the database has all the right info. Ultimately, this episode gets you set up with robust validation and storage for new products, handling tricky edge cases like price formatting behind the scenes.