Events and Listeners in Laravel 11

July 2nd, 2024 • 2 minutes read time

Laravel 11 slightly changes the way we register events and listeners. Here are the differences between previous versions of Laravel and now.

There's no EventServiceProvider in Laravel 11 now. This means that to register events and listeners, you either need to use event discovery or manually register events and listeners inside another service provider.

Here's a reminder of what event/listener registration looks like in Laravel 10:

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

To manually register an event and listener in Laravel 11, open up your AppServiceProvider and do the following:

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

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

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.

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 love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!