In this episode, we take a look at how to hook into the process of creating an order by using events and listeners in Laravel—but with a twist: we use actions as our listeners!
First, we set up an event that's dispatched when an order is created, keeping the responsibilities nice and separated. Traditionally, you'd write a standard event listener to, say, send an order confirmation email, but this time we show an even cleaner approach by turning that listener into a reusable action. Not only does this make your code easier to maintain, but it also opens up the possibility to reuse the same action elsewhere, like from a controller or a console command.
We walk through creating the OrderCreated
event, then create the SendOrderEmail
action and register it as a listener for the event. By introducing the asListener
method, we show how to tailor what happens when your action is used as a listener versus being used directly.
Finally, we tie it all together by creating a really simple email and firing it off (well, logging it, so you don't get spammed!), just to prove the concept works. By the end of the video, you'll see how seamlessly you can combine actions, events, and listeners in a flexible way in Laravel.