Before Laravel 11, I used to bind listeners to events inside the AppProvidersEventServiceProvider
provider class, for example:
<?php
namespace AppProviders;
use AppEventsMyEvent;
use AppListenersMyListener;
use IlluminateFoundationSupportProvidersEventServiceProvider as ServiceProvider;
use IlluminateHttpClientEventsResponseReceived;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
MyEvent::class => [
MyListener::class
]
];
}
In Laravel 11, this binding isn’t necessary at all since Laravel auto-discovery feature auto-discovers the listeners from the app/Listeners
directory. How can I instruct Laravel to auto-discover listeners from a different directory such as app/Domain/Listeners
?
2
Answers
Starting from Laravel 11, you can call the
withEvents()
method inside yourbootstrap/app.php
file to instruct the framework to auto-discover listeners within one or more directories.This method takes an array of paths that will be used to auto-discover listeners, for example here we're telling Laravel to auto-discover all listeners within the
app/Domain/Listeners
directory:This is mentioned in the documentation here: https://laravel.com/docs/11.x/events#event-discovery
Use the
withEvents()
method inside theapp.php
file, for example: