Laravel events listeners let one part of your app say “this happened” without knowing who cares. When an invoice gets paid, the billing code shouldn’t need to know that a receipt goes out and revenue gets recorded. It dispatches one event, and each of those jobs becomes a listener you can add, remove or queue without touching the payment code.
This post builds that flow with real code: a domain event, an action that dispatches it, a sync listener, a queued listener, and the tests that prove it all works. It’s the event-driven piece of my guide to Laravel architecture for large applications, where features talk through small, clear contracts instead of calling each other directly.
What I ran this on
| Tool | Version |
|---|---|
| Laravel Framework | 13.43.0 (fresh laravel/laravel skeleton) |
| PHP | 8.4.27 (CLI) |
| PHPUnit | 12.5.45 |
| Database in tests | SQLite in memory (the skeleton’s phpunit.xml default) |
All 8 tests below pass on that setup. The code uses constructor property promotion and readonly properties, so you need PHP 8.1 or newer, which every supported Laravel version already requires.
Laravel events and listeners: the moving parts
An event is a plain class that carries data. A listener is a class with a handle() method that type-hints the event. Artisan scaffolds both:
php artisan make:event InvoicePaid
php artisan make:listener SendPaymentReceipt --event=InvoicePaid --queued
php artisan make:listener RecordRevenue --event=InvoicePaid
You don’t register anything. Since Laravel 11, listeners in app/Listeners are discovered by reading the type-hint on handle(). To see what’s wired, run event:list. This is the real output from the test app:
$ php artisan event:list --event=InvoicePaid
App\Events\InvoicePaid
⇂ App\Listeners\SendPaymentReceipt@handle (ShouldQueue)
⇂ App\Listeners\RecordRevenue@handle
In production, php artisan optimize (or event:cache) caches this map so discovery doesn’t scan the folder on every request. If you add a listener and it never runs after a deploy, a stale event cache is the first thing I’d check.
Dispatching domain events from an action
A domain event describes a business fact in past tense: InvoicePaid, not SendReceipt. The name should still make sense if every current listener were deleted. Here’s the event:
namespace App\Events;
use App\Models\Invoice;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class InvoicePaid implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(
public readonly Invoice $invoice,
public readonly string $paidVia,
) {}
}
It carries the invoice and how it was paid. SerializesModels matters once a queued listener receives the event: Laravel stores the model’s class and ID and loads a fresh copy when the job runs. If you need the data exactly as it was at dispatch time, pass a readonly object instead, the same approach I used for queued jobs in my post on data transfer objects in Laravel.
The event is dispatched from a single action class, so there’s one place where “an invoice became paid” can happen:
class MarkInvoicePaid
{
public function handle(Invoice $invoice, string $paidVia): Invoice
{
if ($invoice->isPaid()) {
return $invoice; // webhooks retry; don't fire the event twice
}
return DB::transaction(function () use ($invoice, $paidVia) {
$invoice->update(['status' => 'paid', 'paid_at' => now()]);
InvoicePaid::dispatch($invoice, $paidVia);
return $invoice;
});
}
}
Two details here are easy to miss. The early return makes the action idempotent. Payment webhooks get retried, and without that check a retry would fire InvoicePaid again and send a second receipt. If two webhooks can arrive at the same moment, re-check the status inside the transaction with lockForUpdate(); I kept the example simple. And the event implements ShouldDispatchAfterCommit, so Laravel holds it until the surrounding transaction commits. If anything rolls the transaction back, the event never fires, and no listener emails a customer about a payment the database doesn’t have.
I checked that second point the hard way. With the interface removed, the rollback test further down fails with “The unexpected [App\Events\InvoicePaid] event was dispatched.” With it in place, the test passes.
Sync listeners for work that has to happen now
Not every listener should be queued. Recording revenue is quick, uses the same database, and other code may read it right after the request. A plain listener runs inline during dispatch:
class RecordRevenue
{
public function handle(InvoicePaid $event): void
{
DB::table('revenue_entries')->insertOrIgnore([
'invoice_id' => $event->invoice->id,
'amount_cents' => $event->invoice->amount_cents,
'currency' => $event->invoice->currency,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
The revenue_entries.invoice_id column has a unique index, and insertOrIgnore means a duplicate event can’t create a second row. Write every listener as if it might run twice, because sooner or later one will.
Because the event is dispatched after commit, this insert runs after the payment transaction has committed, not inside it. If the two writes must succeed or fail together, write the revenue row in the action itself. A listener is the right home for side effects, not for a core write. Validation belongs before any of this, in the request layer, as covered in my post on Laravel form requests beyond validation.
Queued listeners for slow or flaky work
Sending email talks to an outside service. It can be slow, and it can fail. Implementing ShouldQueue turns the listener into a job, so the payment request returns right away and a worker sends the receipt:
class SendPaymentReceipt implements ShouldQueue
{
use InteractsWithQueue;
public string $queue = 'mail';
public int $tries = 3;
public array $backoff = [10, 60];
public function shouldQueue(InvoicePaid $event): bool
{
return $event->paidVia !== 'manual';
}
public function handle(InvoicePaid $event): void
{
Mail::to($event->invoice->customer_email)
->send(new PaymentReceipt($event->invoice));
}
public function failed(InvoicePaid $event, Throwable $e): void
{
Log::warning('Receipt not sent', [
'invoice' => $event->invoice->number,
'error' => $e->getMessage(),
]);
}
}
What each part does:
$queue = 'mail'puts receipts on their own queue, so a backlog of reports or imports doesn’t delay them.$triesand$backoffretry a failing mail server after 10 seconds, then 60, and then stop.shouldQueue()runs at dispatch time, before anything is pushed. Manual payments recorded by staff skip the receipt, and no job is created at all.failed()runs once the retries are used up. Log something you can act on, here the invoice number.
Queued listeners need a running worker. With the skeleton’s default database connection that’s php artisan queue:work --queue=mail,default. My notes on running Laravel queue workers in production cover Supervisor, timeouts and restarts after deploys.
Testing with Event::fake
The tests answer three questions. Does the action dispatch the right event? Are the listeners wired to it? Does each listener do its job? Keeping those apart is what makes event-driven code pleasant to test.
public function test_it_dispatches_invoice_paid(): void
{
Event::fake([InvoicePaid::class]);
$invoice = Invoice::factory()->create();
(new MarkInvoicePaid)->handle($invoice, 'stripe');
Event::assertDispatchedTimes(InvoicePaid::class, 1);
Event::assertDispatched(InvoicePaid::class, fn (InvoicePaid $e) => $e->invoice->is($invoice) && $e->paidVia === 'stripe');
$this->assertTrue($invoice->fresh()->isPaid());
}
public function test_listeners_are_wired(): void
{
Event::fake();
Event::assertListening(InvoicePaid::class, SendPaymentReceipt::class);
Event::assertListening(InvoicePaid::class, RecordRevenue::class);
}
Event::fake([InvoicePaid::class]) fakes only that event. Everything else, including Eloquent model events, still runs for real. Calling Event::fake() with no list fakes every event, which can quietly switch off model observers your test depends on, so I pass a list unless the test is only checking wiring. assertListening is that wiring check: it fails if someone renames a listener or moves it out of the discovery path.
The rollback test is the one that protects ShouldDispatchAfterCommit:
public function test_no_event_when_the_transaction_rolls_back(): void
{
Event::fake([InvoicePaid::class]);
$invoice = Invoice::factory()->create();
try {
DB::transaction(function () use ($invoice) {
(new MarkInvoicePaid)->handle($invoice, 'stripe');
throw new \RuntimeException('payment row failed to save');
});
} catch (\RuntimeException) {
}
Event::assertNotDispatched(InvoicePaid::class);
$this->assertFalse($invoice->fresh()->isPaid());
}
For the queued listener, fake the queue instead of the events. The event then dispatches for real, the sync listener runs, and the queued one shows up as a CallQueuedListener job you can inspect. If your listeners call outside APIs over HTTP, the same idea applies with the fakes from my post on testing external APIs with Http::fake.
public function test_receipt_listener_is_queued_on_the_mail_queue(): void
{
Queue::fake();
$invoice = Invoice::factory()->create();
(new MarkInvoicePaid)->handle($invoice, 'stripe');
Queue::assertPushedOn('mail', CallQueuedListener::class,
fn (CallQueuedListener $job) => $job->class === SendPaymentReceipt::class);
// the sync listener already ran
$this->assertDatabaseHas('revenue_entries', ['invoice_id' => $invoice->id, 'amount_cents' => 49900]);
}
public function test_receipt_listener_sends_the_mail(): void
{
Mail::fake();
$invoice = Invoice::factory()->create(['customer_email' => 'ayesha@example.com']);
(new SendPaymentReceipt)->handle(new InvoicePaid($invoice, 'stripe'));
Mail::assertSent(PaymentReceipt::class, fn ($mail) => $mail->hasTo('ayesha@example.com'));
}
The second test calls handle() directly. A listener is a plain class, so you don’t need the event system to test what it does. The suite also covers manual payments skipping the receipt, a double payment firing the event only once, and a full run on the sync queue:
$ php artisan test
Tests\Feature\InvoicePaidListenersTest (4 tests)
Tests\Feature\MarkInvoicePaidTest (4 tests)
OK (8 tests, 15 assertions)
When a Laravel event-driven design is the wrong tool
Events hide control flow. Reading MarkInvoicePaid doesn’t tell you a receipt goes out. You have to know to run event:list. That trade is worth it when:
- Several unrelated features react to the same fact, and the list keeps growing.
- The reacting work can be slow or fail without failing the main action.
- Different teams or modules own the reactions.
It’s not worth it when the caller needs a return value, when there’s exactly one reaction and always will be, or when the work must share a transaction with the main write. In those cases a direct method call is clearer, and you can still turn it into an event later.
What I didn’t test
- Broadcasting the event over websockets.
ShouldBroadcastis a separate topic. - A real Redis or SQS queue. The tests use
Queue::fake()and the sync driver; the listener code doesn’t change between drivers. - Event sourcing or storing events for replay. The events here are notifications, not a log of record.
The Laravel events documentation has the full list of listener options, including queued listener middleware, encryption and $maxExceptions. Start with one event for one business fact, keep listeners idempotent, and test the dispatch and the listeners separately.
I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products with Laravel. You can find me on X, LinkedIn, Peerlist and GitHub.
