Master Laravel Events: From Registration to Queued Listeners
This guide explains how Laravel's event system enables decoupled architecture by showing how to register events and listeners, generate code with Artisan, use wildcard listeners, define event and listener classes, control propagation, queue listeners, handle failures, dispatch events, and implement event subscribers.
Laravel implements a lightweight observer pattern that allows you to decouple business logic by publishing events and attaching listeners.
Registering Events and Listeners
The EventServiceProvider contains a $listen array that maps event classes to one or more listener classes. Adding an OrderShipped event with a SendShipmentNotification listener looks like this:
protected $listen = [
'App\Events\OrderShipped' => [
'App\Listeners\SendShipmentNotification',
],
];Generating Event and Listener Classes
Run the Artisan command below to generate all event and listener classes referenced in $listen. Existing files are left untouched:
php artisan event:generateManual Registration and Wildcard Listeners
You may also register listeners directly in the provider’s boot method using Event::listen. Wildcard listeners capture multiple events that match a pattern:
Event::listen('event.*', function ($eventName, array $data) {
// handle any event whose name matches the pattern
});Defining an Event Class
An event class is a simple data container. The example below stores an Order model and uses the SerializesModels trait so the model can be safely serialized when the event is queued.
<?php
namespace App\Events;
use App\Order;
use Illuminate\Queue\SerializesModels;
class OrderShipped
{
use SerializesModels;
public $order;
public function __construct(Order $order)
{
$this->order = $order;
}
}Defining a Listener
The listener receives the event instance in its handle method. The example accesses the order via $event->order and can perform any action such as sending a notification.
<?php
namespace App\Listeners;
use App\Events\OrderShipped;
class SendShipmentNotification
{
public function __construct() {}
public function handle(OrderShipped $event)
{
// $event->order contains the Order model
// e.g., send Slack, email, etc.
}
}Stopping Event Propagation
If a listener’s handle method returns false, Laravel will prevent any subsequent listeners for that event from being executed.
Queued Listeners
For time‑consuming tasks, make the listener implement Illuminate\Contracts\Queue\ShouldQueue. Laravel will then dispatch the listener as a queued job.
<?php
namespace App\Listeners;
use App\Events\OrderShipped;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendShipmentNotification implements ShouldQueue
{
// optional: specify a custom queue connection and name
public $connection = 'sqs';
public $queue = 'listeners';
}If you need to manually delete or release the queued job, add the InteractsWithQueue trait and call its methods inside handle:
<?php
namespace App\Listeners;
use App\Events\OrderShipped;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendShipmentNotification implements ShouldQueue
{
use InteractsWithQueue;
public function handle(OrderShipped $event)
{
// Example: release the job back to the queue after 30 seconds
$this->release(30);
}
}Handling Failed Jobs
If a queued listener exceeds the maximum retry attempts, Laravel calls a failed method on the listener. The method receives the original event instance and the exception that caused the failure.
<?php
namespace App\Listeners;
use App\Events\OrderShipped;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendShipmentNotification implements ShouldQueue
{
use InteractsWithQueue;
public function handle(OrderShipped $event) { /* ... */ }
public function failed(OrderShipped $event, $exception)
{
// Log the failure, alert, or perform cleanup
}
}Dispatching an Event
Use the global event() helper to fire an event from anywhere in the application:
<?php
namespace App\Http\Controllers;
use App\Order;
use App\Events\OrderShipped;
use App\Http\Controllers\Controller;
class OrderController extends Controller
{
public function ship($orderId)
{
$order = Order::findOrFail($orderId);
// ...order shipping logic...
event(new OrderShipped($order));
}
}Event Subscribers
A subscriber class can listen to multiple events by defining a subscribe method that registers callbacks on the event dispatcher.
<?php
namespace App\Listeners;
class UserEventSubscriber
{
public function onUserLogin($event) { /* ... */ }
public function onUserLogout($event) { /* ... */ }
public function subscribe($events)
{
$events->listen('Illuminate\Auth\Events\Login', 'App\Listeners\UserEventSubscriber@onUserLogin');
$events->listen('Illuminate\Auth\Events\Logout', 'App\Listeners\UserEventSubscriber@onUserLogout');
}
}Register the subscriber in EventServiceProvider via the $subscribe array:
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [];
protected $subscribe = [
'App\Listeners\UserEventSubscriber',
];
}These mechanisms provide a flexible, decoupled way to build event‑driven Laravel applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
