laraveleventslistenerlaravel-11

Laravel 11 - Auto discovery of event listeners inside a custom directory


Before Laravel 11, I used to bind listeners to events inside the App\Providers\EventServiceProvider provider class, for example:

<?php

namespace App\Providers;

use App\Events\MyEvent;
use App\Listeners\MyListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Http\Client\Events\ResponseReceived;

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 ?


Solution

  • Starting from Laravel 11, you can call the withEvents() method inside your bootstrap/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:

    <?php
    
    use Illuminate\Foundation\Application;
    use Illuminate\Foundation\Configuration\Exceptions;
    use Illuminate\Foundation\Configuration\Middleware;
    
    return Application::configure(basePath: dirname(__DIR__))
        ->withRouting(
            web: __DIR__.'/../routes/web.php',
            commands: __DIR__.'/../routes/console.php',
            channels: __DIR__.'/../routes/channels.php',
            health: '/up',
        )->withEvents(discover: [
            app_path('Domain/Listeners')
        ])->create();
    

    This is mentioned in the documentation here: https://laravel.com/docs/11.x/events#event-discovery