In this episode, we take our knowledge of events in Livewire and put it into practice by getting our components to talk to each other!
First, we clean up our code by splitting the book creation form out of our main book index component and moving it into its own CreateBook
component. This helps keep our code organized as the app grows, making maintenance easier.
After moving the form, we notice that the list of books doesn't automatically update when a new book is added. That's because, now that the form and the list are in separate components, they don't automatically communicate. To fix this, we start using events! When a new book is created in the CreateBook
component, we dispatch an event called book.created
. On the book index side, we listen for this event and re-render the list whenever it fires.
We also explore passing data with events—like sending the new book's ID so we could (if we wanted) display a confirmation or add the book to a local collection. You get to see both simple and more detailed ways to listen for and handle events, including Livewire’s handy $refresh
magic method for quick component updates.
By the end of the episode, you’ll see just how powerful events can be for keeping your UI responsive and your codebase tidy. Plus, you’ll have a pattern you can reuse as your Livewire projects grow!