Events
Introduction
Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Event classes are typically stored in the app/Events
directory, while their listeners are stored in app/Listeners
. Don't worry if you don't see these directories in your application as they will be created for you as you generate events and listeners using Artisan console commands.
Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an App\Events\OrderShipped
event which a listener can receive and use to dispatch a Slack notification.
Registering Events & Listeners
The App\Providers\EventServiceProvider
included with your Laravel application provides a convenient place to register all of your application's event listeners. The listen
property contains an array of all events (keys) and their listeners (values). You may add as many events to this array as your application requires. For example, let's add an OrderShipped
event:
use App\Events\OrderShipped;
use App\Listeners\SendShipmentNotification;
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
OrderShipped::class => [
SendShipmentNotification::class,
],
];
The event:list
command may be used to display a list of all events and listeners registered by your application.
Generating Events & Listeners
Of course, manually creating the files for each event and listener is cumbersome. Instead, add listeners and events to your EventServiceProvider
and use the event:generate
Artisan command. This command will generate any events or listeners that are listed in your EventServiceProvider
that do not already exist:
php artisan event:generate
Alternatively, you may use the make:event
and make:listener
Artisan commands to generate individual events and listeners:
php artisan make:event PodcastProcessed
php artisan make:listener SendPodcastNotification --event=PodcastProcessed
Manually Registering Events
Typically, events should be registered via the EventServiceProvider
$listen
array; however, you may also register class or closure based event listeners manually in the boot
method of your EventServiceProvider
:
use App\Events\PodcastProcessed;
use App\Listeners\SendPodcastNotification;
use Illuminate\Support\Facades\Event;
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
Event::listen(
PodcastProcessed::class,
[SendPodcastNotification::class, 'handle']
);
Event::listen(function (PodcastProcessed $event) {
//
});
}
Queueable Anonymous Event Listeners
When registering closure based event listeners manually, you may wrap the listener closure within the Illuminate\Events\queueable
function to instruct Laravel to execute the listener using the queue:
use App\Events\PodcastProcessed;
use function Illuminate\Events\queueable;
use Illuminate\Support\Facades\Event;
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
Event::listen(queueable(function (PodcastProcessed $event) {
//
}));
}
Like queued jobs, you may use the onConnection
, onQueue
, and delay
methods to customize the execution of the queued listener:
Event::listen(queueable(function (PodcastProcessed $event) {
//
})->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10)));
If you would like to handle anonymous queued listener failures, you may provide a closure to the catch
method while defining the queueable
listener. This closure will receive the event instance and the Throwable
instance that caused the listener's failure:
use App\Events\PodcastProcessed;
use function Illuminate\Events\queueable;
use Illuminate\Support\Facades\Event;
use Throwable;
Event::listen(queueable(function (PodcastProcessed $event) {
//
})->catch(function (PodcastProcessed $event, Throwable $e) {
// The queued listener failed...
}));
Wildcard Event Listeners
You may even register listeners using the *
as a wildcard parameter, allowing you to catch multiple events on the same listener. Wildcard listeners receive the event name as their first argument and the entire event data array as their second argument:
Event::listen('event.*', function ($eventName, array $data) {
//
});
Event Discovery
Instead of registering events and listeners manually in the $listen
array of the EventServiceProvider
, you can enable automatic event discovery. When event discovery is enabled, Laravel will automatically find and register your events and listeners by scanning your application's Listeners
directory. In addition, any explicitly defined events listed in the EventServiceProvider
will still be registered.
Laravel finds event listeners by scanning the listener classes using PHP's reflection services. When Laravel finds any listener class method that begins with handle
, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature:
use App\Events\PodcastProcessed;
class SendPodcastNotification
{
/**
* Handle the given event.
*
* @param \App\Events\PodcastProcessed $event
* @return void
*/
public function handle(PodcastProcessed $event)
{
//
}
}
Event discovery is disabled by default, but you can enable it by overriding the shouldDiscoverEvents
method of your application's EventServiceProvider
:
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return true;
}
By default, all listeners within your application's app/Listeners
directory will be scanned. If you would like to define additional directories to scan, you may override the discoverEventsWithin
method in your EventServiceProvider
:
/**
* Get the listener directories that should be used to discover events.
*
* @return array
*/
protected function discoverEventsWithin()
{
return [
$this->app->path('Listeners'),
];
}
Event Discovery In Production
In production, it is not efficient for the framework to scan all of your listeners on every request. Therefore, during your deployment process, you should run the event:cache
Artisan command to cache a manifest of all of your application's events and listeners. This manifest will be used by the framework to speed up the event registration process. The event:clear
command may be used to destroy the cache.
Defining Events
An event class is essentially a data container which holds the information related to the event. For example, let's assume an App\Events\OrderShipped
event receives an Eloquent ORM object:
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderShipped
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* The order instance.
*
* @var \App\Models\Order
*/
public $order;
/**
* Create a new event instance.
*
* @param \App\Models\Order $order
* @return void
*/
public function __construct(Order $order)
{
$this->order = $order;
}
}
As you can see, this event class contains no logic. It is a container for the App\Models\Order
instance that was purchased. The SerializesModels
trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP's serialize
function, such as when utilizing queued listeners.
Defining Listeners
Next, let's take a look at the listener for our example event. Event listeners receive event instances in their handle
method. The event:generate
and make:listener
Artisan commands will automatically import the proper event class and type-hint the event on the handle
method. Within the handle
method, you may perform any actions necessary to respond to the event:
<?php
namespace App\Listeners;
use App\Events\OrderShipped;
class SendShipmentNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param \App\Events\OrderShipped $event
* @return void
*/
public function handle(OrderShipped $event)
{
// Access the order using $event->order...
}
}
Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Laravel service container, so dependencies will be injected automatically.