In this episode, we tackle some code duplication in our update book component by reusing our existing book form class for both creating and updating books. Up until now, we had separate logic and repeated validation rules. Instead, we're refactoring so all logic and validation lives in our reusable book form, which can handle both scenarios.
First, we look at how we were assigning properties and validating individually, and then demo a cool shorthand to mass assign properties using the only
and fill
helpers in Livewire. This makes grabbing and updating the fields way more concise. But then, rather than sticking with that, we step it up by moving our state and methods into the book form class.
We walk through making our form handle both create and update actions by passing in an existing book and making sure our properties get properly filled for editing. That way, when you hit edit, the values actually show up! Then, we ensure that submission validates the values using a single set of rules and hits the right update or create logic.
The real win is that everything for book creation and updating now lives in one place, so it's less code and way easier to maintain or change later. Plus, you see how convenient Livewire makes it to keep things DRY! By the end, we can edit and save books easily, and our code is much cleaner and more organized.