In this episode, we see how to make our modal approach a lot more flexible by creating a trait that we can reuse for any modal we build. We start by building a second modal component, just to illustrate where things get repetitive and could use some tidying up.
After setting up the basic second modal, we realize a lot of the logic we used in the first modal—like showing and hiding the modal—is going to be needed everywhere. Instead of copying and pasting code, we refactor by moving this logic into a trait. We create a new trait (called IsModal
) under our Traits
folder in the Livewire directory and move all our reusable modal functionality there.
With this trait in place, adding modal functionality to any Livewire component is as easy as using the trait in that component. We show how to update both our first and second modals to use the trait, clean up the code, and then add a button to the dashboard to trigger the new modal. Finally, we test everything and see that both modals can be opened and closed independently, demonstrating how much easier it is to reuse modal logic now!