Events Decouple Your Code
"Something happened" → "Do these things"
Creating Events
php artisan make:event OrderPlaced
php artisan make:listener SendOrderConfirmation --event=OrderPlaced
// Events/OrderPlaced.php
class OrderPlaced
{
public function __construct(
public Order $order
) {}
}
Creating Listeners
// Listeners/SendOrderConfirmation.php
class SendOrderConfirmation
{
public function handle(OrderPlaced $event): void
{
Mail::to($event->order->user)->send(
new OrderConfirmationMail($event->order)
);
}
}
Registering
// EventServiceProvider
protected $listen = [
OrderPlaced::class => [
SendOrderConfirmation::class,
UpdateInventory::class,
NotifyWarehouse::class,
],
];
Dispatching
// Anywhere in your code
event(new OrderPlaced($order));
// Or
OrderPlaced::dispatch($order);
Queued Listeners
For heavy work:
class SendOrderConfirmation implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
// Runs in background
}
}
Event Subscribers
Group related listeners:
class OrderEventSubscriber
{
public function handleOrderPlaced(OrderPlaced $event) {}
public function handleOrderShipped(OrderShipped $event) {}
public function subscribe(Dispatcher $events): array
{
return [
OrderPlaced::class => 'handleOrderPlaced',
OrderShipped::class => 'handleOrderShipped',
];
}
}
When to Use Events
- Multiple things happen after one action
- You want to decouple modules
- Background processing needed
- Audit logging
