skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 IlluminateFoundationApplication;
    use IlluminateFoundationConfigurationExceptions;
    use IlluminateFoundationConfigurationMiddleware;
    
    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


  2. Use the withEvents() method inside the app.php file, for example:

    Application::configure(basePath: dirname(__DIR__))->withEvents(['app/CustomListeners']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search