Events & Listeners — Laravel

An event is an announcement that something happened, and a listener is code that reacts to it. Make them with php artisan make:event BookBorrowed and php…

The school break bell rings once, then the canteen opens, the guard opens the gate, and the students leave class. The bell doesn't know who reacts, and everyone knows their own task.

Laravel works the same way. An event is an announcement that something just happened, for example "a book was borrowed". A listener is code that reacts to that announcement. The ring of the bell is the event, the people who react are the listeners, and the one who rings the bell is the controller.

The problem: a controller that does everything

In the library app, LoanController@store records a loan. Over time it gets more tasks: lower the stock, email the member a receipt, write a log line for the librarian. If all of that lives in the controller, every new task means changing the controller again. The member also waits for the email to go out before the page opens.

With an event, the controller only announces "a book was borrowed". Who reacts is handled in other classes, the listeners.

Your first event and listener

Make both with Artisan:

php artisan make:event BookBorrowed
php artisan make:listener SendLoanReceipt --event=BookBorrowed

This is the event file:

<?php
// app/Events/BookBorrowed.php
namespace App\Events;

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

class BookBorrowed
{
    use Dispatchable, SerializesModels;

    public function __construct(public Loan $loan) {}
}

This is the listener file:

<?php
// app/Listeners/SendLoanReceipt.php
namespace App\Listeners;

use App\Events\BookBorrowed;
use App\Mail\LoanReceipt;
use Illuminate\Support\Facades\Mail;

class SendLoanReceipt
{
    public function handle(BookBorrowed $event): void
    {
        Mail::to($event->loan->user)->send(new LoanReceipt($event->loan));
    }
}

In the controller, the event is announced after the loan is recorded:

// app/Http/Controllers/LoanController.php, inside store()
$loan = Loan::create(['user_id' => $request->user()->id, 'book_id' => $book->id]);

BookBorrowed::dispatch($loan); // announce: a book was borrowed

return response()->json(['id' => $loan->id], 201);

One event, three listeners

Add two more listeners, UpdateBookStock and LogLoanActivity, the same way. The controller doesn't change at all. This is what happens when Budi borrows "The Rainbow Troops" (stock 3), while every listener is still plain (sync, run right away). In this example, the listeners run in this order:

Order What runs Time Result
1 Loan::create(...) in the controller 6 ms loan #12 is recorded
2 UpdateBookStock 5 ms stock 3 becomes 2
3 SendLoanReceipt 1,200 ms receipt email sent to Budi
4 LogLoanActivity 3 ms one line in the log
5 201 response 1,214 ms in total Budi's page finally opens

Sync listeners run one at a time, in the same request. The browser waits for all of them, including the email. The email is slow because it has to talk to a mail server.

Sync or ShouldQueue

A slow task that doesn't have to finish before the response is sent can wait. Add implements ShouldQueue to the listener class (an interface from Laravel that means "put this in the queue"):

use Illuminate\Contracts\Queue\ShouldQueue;

class SendLoanReceipt implements ShouldQueue
{
    public int $tries = 3; // tried at most 3 times

    public function handle(BookBorrowed $event): void
    {
        Mail::to($event->loan->user)->send(new LoanReceipt($event->loan));
    }
}
Sync ShouldQueue
When it runs on dispatch, in that request later, when a worker picks it up
Who waits the browser nobody
If it fails the request answers 500 retried up to $tries
Good for what must be done before the response (stock) what is slow or calls another server (email)

When a listener fails

Say the mail server is not working and SendLoanReceipt is still sync. Mail::send() throws an exception, so:

If the listener is ShouldQueue, the request still answers 201. The job fails in the worker, is tried at most 3 times (as $tries says), then goes into the failed_jobs table.

One more thing: when a listener's handle() returns false, the listeners after it don't run. That's a way to stop on purpose, not an error.

⚠️ Listeners that never run, or run without a word

TL;DR: An event is an announcement that something happened, and a listener is code that reacts to it. Make them with php artisan make:event BookBorrowed and php artisan make:listener SendLoanReceipt --event=BookBorrowed. The event carries data through its constructor (public Loan $loan). The listener reads it in handle(BookBorrowed $event) through $event->loan. The controller only calls BookBorrowed::dispatch($loan) to announce the event. Sync listeners (run right away) run one at a time in the same request, and the browser waits for all of them (1,214 ms in this example, because of the email). A listener with implements ShouldQueue is handed to a worker (a separate process that runs the tasks in the queue), so the response is ready in 18 ms. A failing sync listener makes the request answer 500 and skips the listeners after it, without undoing what already ran.

⚡ An event is only a box of data

Write:

class BookBorrowed
{
    use Dispatchable, SerializesModels;

    public function __construct(public Loan $loan) {}
}

Meaning: An event is an announcement that something just happened, here "a book was borrowed". php artisan make:event BookBorrowed creates the class. An event only carries data about what happened: the data comes in through the constructor and is kept as the $loan property (the loan that was just recorded).

⚡ Listeners react, the controller just announces

Write:

public function handle(BookBorrowed $event): void
{
    Mail::to($event->loan->user)->send(new LoanReceipt($event->loan));
}

Meaning: A listener is code that reacts to an event. This listener emails a receipt (LoanReceipt) to the member who borrowed. The BookBorrowed type in handle() tells Laravel that this listener belongs to the event BookBorrowed, and the data is read through $event->loan. The controller only calls BookBorrowed::dispatch($loan) to announce the event.

In the exercise, you call handle() yourself and print the result with echo.

⚡ Sync waits, ShouldQueue doesn't

Guess first: sync listeners run right away, in the same request. The controller records the loan (6 ms), then three sync listeners run: stock (5 ms), email (1,200 ms) and log (3 ms). How long until the page opens for Budi, the member who borrows?

1,214 ms. Sync listeners run one at a time in the same request, and the browser waits for all of them, the email included.

Meaning: Add implements ShouldQueue to the slow listener. That listener is stored as a job (a task in the queue) and run later by a worker (a separate process). Storing the job takes about 4 ms, so the response takes only 18 ms, not 1,214 ms.

What you will learn