Events and Listeners Changes in Laravel 11 and 12

July 2nd, 2024 • Last updated 2 minutes read time

Laravel 11 and 12 changes the way events and listeners are registered. In this article, we'll cover how Laravel changed events and listeners, starting in Laravel 11.

There's no EventServiceProvider in Laravel 11 and 12 now. It was removed as part of cleaning up the Laravel project skeleton.

This means that to register events and listeners, you either need to:

  • Use event discovery
  • Manually register events and listeners inside another service provider

(We'll be covering both in this article)

Before we start, here's a reminder of what event/listener registration looks like in Laravel 10 and below:

protected $listen = [
    OrderShipped::class => [
        SendShipmentNotification::class,
    ],
];

To manually register an event and listener in Laravel 11 and 12, open up your AppServiceProvider (or any service provider) and do the following:

public function boot(): void
{
    Event::listen(
        OrderShipped::class,
        SendShipmentNotification::class,
    );
}

The first argument is the event you're listening for and the second is the listener you've defined.

Rather than use this approach though, event discovery might be what you're looking for.

Although available in earlier versions, event discovery now seems to be the recommended approach to registering events and listeners. There's an excellent reason for this... you can create your event and listener and not have to manually register anything, so there is less code to write!

Once you've created your event and listener, all you need to do is typehint the event within the handle method of your listener.

use App\Events\OrderShipped;
 
class SendShipmentNotification
{
    public function handle(OrderShipped $event): void
    {
        // ...
    }
}

In this example, whenever an OrderShipped event is fired, the SendShipmentNotification listener's handle method will be invoked.

This approach isn't for everyone. Some people will prefer manually registering so there's a clear list of event/listeners.

Laravel scans your Listeners directory, and as long as your listeners have an __invoke magic method or handle method, it'll use reflection to work out which events it needs to respond to based on the type hint for the $event you've given.

Laravel simplifies how your events and listeners connect by allowing you to write less boilerplate code. However, the option remains if you need (or want) to manually register events and listeners.

If you found this article helpful, you'll probably love our practical screencasts!
Author
Alex Garrett-Smith

Comments

No comments, yet. Be the first!