In this episode, we're tackling the job of deleting a book in our Livewire app – but more importantly, we're looking at the best way to wire this up between our child and parent components (with a little bonus discussion on security coming later).
First, we try doing the delete operation right inside the child (BookItem
) component. While this works — it actually deletes the book in the database — it doesn't update the parent list until a manual page refresh, which isn't ideal.
To fix this, we look at dispatching events from the child to the parent (BookIndex
) component, so when a book is deleted, the parent knows to update itself. That works, but it feels a bit heavy for something as simple as deleting a book.
That's when we introduce the real star: Livewire's magic $parent
functionality. Using $this->parent->deleteBook($bookId)
, the child component can directly call a method on its parent. This massively simplifies our code — there's no need for extra events or listeners, just a straight-up parent method call. It's super clean, and makes re-rendering the book list straightforward and efficient.
We wrap up with a quick look at how well this performs (spoiler: Livewire only re-renders what's needed), and note that next time, we really need to lock this deletion process down with proper authorization (otherwise anyone could delete any book — not good!).
So in summary: This lesson is all about calling parent component methods from a child in Livewire, making our components work together nicely and efficiently. Authorization is coming up next!