Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Auto discovery of events in Laravel

In this article, I’ve written about how to use event subscribers or observer pattern in Laravel.

So basically, one can write the Events and register them along with their listeners in app/Providers/EventServiceProvider class, under $listen like so.

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\OrderCanceled' => [
        'App\Listeners\SendOrderCancelEmail',
        'App\Listeners\InitiateOrderRefund',
    ],
];

As the Events grows so as this $listen property. And there would be a good chance, you might forget to register the event.

Auto Discovering Events

To overcome the above issue, Laravel comes with the auto discovery of the events and respective listeners of those events. But the feature is not enabled by default.

This can be enabled by overriding the shouldDiscoverEvents method of your application’s app/Providers/EventServiceProvider by returning true from it like so.

/**
 * Determine if events and listeners should be automatically discovered.
 *
 * @return bool
 */
public function shouldDiscoverEvents()
{
    return true;
}

Once done, 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.

Behind the scenes, Laravel identfies events and listeners by scanning Event and Listener directories using PHP’s Reflection.

Auto-discovery with custom directories

By default, all listeners within your application’s Listeners directory will be scanned. If you would like to define additional directories to scan, you may override the discoverEventsWithin method in your EventServiceProvider like so.

/**
 * Get the listener directories that should be used to discover events.
 *
 * @return array
 */
protected function discoverEventsWithin()
{
    return [
        $this->app->path('Listeners'),
    ];
}
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?