In this episode, we're focusing on how to revive or "hydrate" the product state when editing an existing product in our app. We'll make sure that when you open the edit form for a product, all of its details (like name, price, etc.) are loaded correctly from the model and displayed in the form so you can update them.
We start by pulling the product's data from the database and using Laravel's Livewire mount hook to set up our component's state with the product's array version. Important note: we avoid pulling in any related models (just the product itself) by using without relations
and toArray
.
You’ll notice that when we do this, the price comes up looking a bit odd—it's in cents, not dollars. To fix this, we dive into configuring the product price to display correctly using the Laravel Money package. This package makes working with monetary values a breeze, handling formatting between cents and dollars, and giving us helper functions for Blade templates and controllers.
We quickly demo how the Money package works, showing how to convert cents into formatted dollar strings. After a bit of tweaking to our accessor in the Product model, whenever we get the product's price, we now have a Money instance, making it super simple to display it properly in the form.
With this set up, when we go to edit a product, everything is pre-filled with the correct values, including a nicely formatted price, making the editing experience seamless.