Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 67 ยท Queues, Events and Notifications

Events and Listeners

Learn Laravel events: event classes, listeners, queued listeners, subscribers, afterCommit, and Event::fake, with a runnable dispatcher stand-in.

When something important happens in your app, such as a user registering or an order shipping, several other things usually need to happen. Send a welcome email. Create a default workspace. Tell the analytics system. If the registration code does all of that itself, it grows every time someone wants a new reaction, and it has to know about every part of the app.

Events solve this. The code that makes the thing happen announces it with a small object, an event. Listeners subscribe to that event and react. The announcer does not know who is listening. The general pattern is explained in event dispatching; here you will see how Laravel packages it.

Laravel cannot run on this site, so Laravel code blocks are read-only. The runnable examples are plain PHP stand-ins for the same ideas, and each section says which is which.

The flow

sequenceDiagram
    participant C as Controller
    participant D as Event dispatcher
    participant L1 as SendWelcomeEmail
    participant L2 as CreateWorkspace
    C->>D: event(new UserRegistered($user))
    D->>L1: handle($event)
    D->>L2: handle($event)
    D-->>C: returns

The controller only knows the dispatcher. The dispatcher finds the listeners for the event class.

Creating an event

An event is a plain PHP class. It carries the data its listeners need, usually models or IDs, and has no behavior of its own.

Terminal
php artisan make:event OrderShipped
php artisan make:listener SendShipmentNotification --event=OrderShipped
PHP
<?php

namespace App\Events;

use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderShipped
{
    use Dispatchable, SerializesModels;

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

Dispatchable adds a static dispatch() method, so you can write OrderShipped::dispatch($order). SerializesModels matters when the event travels through a queue: it stores model identifiers instead of whole models. Name events in the past tense, because they describe something that already happened: OrderShipped, PasswordChanged, InvoicePaid.

Listeners

A listener is a class with a handle() method that receives the event:

PHP
<?php

namespace App\Listeners;

use App\Events\OrderShipped;
use App\Services\ShipmentNotifier;

class SendShipmentNotification
{
    public function __construct(private ShipmentNotifier $notifier)
    {
    }

    public function handle(OrderShipped $event): void
    {
        $this->notifier->notify($event->order);
    }
}

The constructor is resolved through the service container, so you can type-hint dependencies there; handle() can also type-hint extra services.

Discovery. Laravel finds listeners automatically. It scans app/Listeners, and any public method named handle or __invoke whose first parameter is type-hinted with an event class is registered for that event. You rarely need to register anything by hand. When you do want an explicit mapping, for example for a closure or a listener outside that folder, use Event::listen() in a service provider's boot() method:

PHP
use App\Events\OrderShipped;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    Event::listen(OrderShipped::class, SendShipmentNotification::class);

    Event::listen(function (OrderShipped $event) {
        // a closure listener; the type hint chooses the event
    });
}

You can see what is registered with php artisan event:list.

Dispatching

PHP
OrderShipped::dispatch($order);   // through Dispatchable
event(new OrderShipped($order));  // the helper

By default, listeners run synchronously, one after another, inside your request. If one of them throws an exception and nobody catches it, the remaining listeners do not run and the request fails. A listener can also stop propagation: returning false from handle() stops the event from reaching later listeners.

Here is a stand-in dispatcher built the way Laravel's works in principle: events are classes, listeners are looked up by the event's class, and dispatch() calls each one.

PHP An event dispatcher stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second dispatch shows early stopping: the blocklist listener returns false, so the analytics listener never runs. In Laravel the same trick works with a listener returning false.

Queued listeners

Some reactions are slow: sending an email, calling an API. Implement ShouldQueue on the listener and Laravel pushes it onto the queue instead of running it in the request:

PHP
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    public string $queue = 'notifications';
    public int $tries = 3;

    public function handle(OrderShipped $event): void
    {
        // runs in a worker
    }

    public function failed(OrderShipped $event, Throwable $exception): void
    {
        // called when all attempts are used up
    }
}

All the queue options from the previous lesson apply: tries, backoff, queue, connection, failed(). Each queued listener becomes its own job, so one failing listener does not take the others down. Because queued listeners can run more than once and later, they must serialize cleanly and should be idempotent.

Events and database transactions

A common bug: you create an order inside a database transaction and dispatch an event that a queued listener handles. The worker is fast, picks the job up before the transaction commits and finds no order. The fix is the ShouldDispatchAfterCommit interface on the event, or implements ShouldQueue plus a public $afterCommit = true property on the listener:

PHP
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;

class OrderPlaced implements ShouldDispatchAfterCommit
{
    use Dispatchable, SerializesModels;

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

Now, if the event is dispatched inside a transaction, it is held until the transaction commits, and discarded if the transaction rolls back. Outside a transaction it is dispatched immediately.

Subscribers

A subscriber is one class that listens to several events, which keeps related reactions together:

PHP
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Events\Dispatcher;

class AuthActivitySubscriber
{
    public function handleLogin(Login $event): void { /* ... */ }

    public function handleLogout(Logout $event): void { /* ... */ }

    public function subscribe(Dispatcher $events): array
    {
        return [
            Login::class => 'handleLogin',
            Logout::class => 'handleLogout',
        ];
    }
}

Register it with Event::subscribe(AuthActivitySubscriber::class) in a service provider. Laravel also fires many events by itself: Login, Registered, PasswordReset, MigrationsEnded, and the model events of Eloquent. You listen to those exactly like your own.

Testing with Event::fake

Real listeners send mail and call APIs, which you do not want in tests. Event::fake() replaces the dispatcher with a recorder, so you can check what was dispatched:

PHP
use App\Events\OrderShipped;
use Illuminate\Support\Facades\Event;

it('announces shipped orders', function () {
    Event::fake();

    $order = Order::factory()->create();
    $this->post("/orders/{$order->id}/ship");

    Event::assertDispatched(OrderShipped::class, fn ($e) => $e->order->is($order));
    Event::assertNotDispatched(OrderCancelled::class);
});

Call Event::fake([OrderShipped::class]) to fake only some events. The idea of a fake that records instead of acting is shown in faking and mocking. This stand-in shows the pattern:

PHP A recording fake dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

When not to use events

Events are easy to overuse. They make flow harder to follow, because reading OrderShipped::dispatch() does not tell you what happens next. Use them when several independent parts of the app react to something, or when you want to queue the reactions. For a single, always-needed step, just call a method or an action class.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why name an event OrderShipped rather than ShipOrder?

    An event is an announcement of a fact. Past-tense names keep the intent clear and separate events from commands or jobs.
  2. 2. How do you make a listener run in a queue worker instead of during the request?

    A listener that implements ShouldQueue is pushed onto the queue and run by a worker, with the usual tries, backoff and failed() options.
  3. 3. A queued listener for an event dispatched inside a transaction sometimes cannot find the new row. What helps?

    The worker can start before the transaction commits. Dispatching after commit holds the event until the data is visible, and drops it on rollback.
  4. 4. What does Event::fake() do in a test?

    The faked dispatcher records events without calling listeners, so tests stay fast and free of side effects, and you can use assertDispatched and assertNotDispatched.

Summary

  • An event is a small past-tense class; listeners react to it, and the dispatcher connects them.
  • Laravel auto-discovers listeners from type-hinted handle() methods; event:list shows them, Event::listen() registers extras.
  • Listeners run synchronously by default; ShouldQueue moves them to workers.
  • Use ShouldDispatchAfterCommit when an event is raised inside a transaction.
  • Subscribers group several listeners; Event::fake() records events in tests.
  • Prefer a plain method call when only one thing must happen.

Next: Sending Mail