php 44 lines · 6 steps

How event subscribers group listeners in Laravel

A single subscriber class handles multiple order events by mapping each event to a handler method.

Explained by highlit
1<?php
2 
3namespace App\Listeners;
4 
5use App\Events\OrderPlaced;
6use App\Events\OrderRefunded;
7use App\Jobs\GenerateInvoice;
8use App\Notifications\OrderConfirmation;
9use Illuminate\Events\Dispatcher;
10use Illuminate\Support\Facades\Log;
11 
12class OrderEventSubscriber
13{
14 public function handleOrderPlaced(OrderPlaced $event): void
15 {
16 $order = $event->order;
17 
18 $order->customer->notify(new OrderConfirmation($order));
19 GenerateInvoice::dispatch($order)->onQueue('billing');
20 
21 $order->warehouse->reserveStock($order->lineItems);
22 }
23 
24 public function handleOrderRefunded(OrderRefunded $event): void
25 {
26 $order = $event->order;
27 
28 $order->payment->issueRefund($event->amount);
29 $order->warehouse->releaseStock($order->lineItems);
30 
31 Log::channel('finance')->info('Order refunded', [
32 'order_id' => $order->id,
33 'amount' => $event->amount->format(),
34 ]);
35 }
36 
37 public function subscribe(Dispatcher $events): array
38 {
39 return [
40 OrderPlaced::class => 'handleOrderPlaced',
41 OrderRefunded::class => 'handleOrderRefunded',
42 ];
43 }
44}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A subscriber class consolidates related event handlers so one bounded context lives in one place.
  2. 2Dispatching jobs to a named queue keeps slow side effects off the request path.
  3. 3The subscribe method's array is the contract that wires events to methods, keeping registration declarative.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How event subscribers group listeners in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code