← Back to Course

Creating and Dispatching Events

With the concept of events and listeners understood, the next step is generating the actual classes and triggering them from application code.

Generating Event and Listener Classes

php artisan make:event OrderShipped
php artisan make:listener SendShipmentNotification --event=OrderShipped

Defining the Event

class OrderShipped
{
    public function __construct(public Order $order) {}
}

Handling It in the Listener

class SendShipmentNotification
{
    public function handle(OrderShipped $event)
    {
        Mail::to($event->order->user)->send(new ShipmentMail($event->order));
    }
}

Dispatching the Event

event(new OrderShipped($order));

By default listeners run synchronously in the same request. Marking a listener with the ShouldQueue interface pushes its work onto a queue instead, which is exactly where the next topic picks up.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course