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);
make:eventcreatesapp/Events/BookBorrowed.php.make:listener ... --event=BookBorrowedcreatesapp/Listeners/SendLoanReceipt.phpwithhandle(BookBorrowed $event)already in it.public function __construct(public Loan $loan) {}: an event is only a box of data. The data comes in through the constructor and is kept as the$loanproperty.handle(BookBorrowed $event): theBookBorrowedtype here tells Laravel that this listener belongs to the eventBookBorrowed. Laravel itself scans theapp/Listenersfolder and registers the listeners in it (event discovery).php artisan event:listshows each event with its listeners.$event->loan: the listener reads the data from the event given tohandle().BookBorrowed::dispatch($loan)announces the event. Thedispatchmethod comes from theDispatchabletrait in the event class. Its arguments go to the event's constructor. It means the same asevent(new BookBorrowed($loan)).
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));
}
}
- On
dispatch, this listener doesn't run. Laravel only stores it as a job (a task waiting to be done) in the queue. Here the queue is thejobstable, because a new project usesQUEUE_CONNECTION=databasein.env. Storing that job takes about 4 ms. - A separate process,
php artisan queue:work, is called a worker. The worker takes that job and runshandle(). The details are in the Queue & Job lesson. - The response is now ready in 6 + 5 + 4 + 3 = 18 ms, no longer 1,214 ms. The email still goes out, just a little after the page.
| 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:
LogLoanActivitynever runs, because in this example it runs afterSendLoanReceipt, and the listeners after the failing one are skipped.- The request answers
500 | Server Error. - What already ran is not undone: loan #12 is recorded and the stock is already lowered. If Budi tries again, he borrows twice.
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
handle()without the event type. WithoutBookBorrowed $event, Laravel doesn't know which event the listener belongs to, and it never runs. Check withphp artisan event:list.ShouldQueuebut still slow, or the email never arrives.QUEUE_CONNECTION=syncruns the job right away, so the request is still slow. When the value isdatabase, a worker has to be running. Without one, the jobs collect in thejobstable.- One listener needs another listener's result. Sync listeners do run one at a time, but with event discovery their order isn't guaranteed. So each listener should work on its own. If the order matters, do the steps in order in one place.
- The text from
handle()doesn't show in the exercise. In the exercise, ahandle()that returns text displays nothing yet. Call it and print it:echo $listener->handle($event);, and read the data through$event->....
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.