A Guide On How & When To Use Event Listening in Laravel 11 with Code Examples

Laravel 11 released lately this year and we see they have improved on many things and the repertoire has much improved than ever before it was. In this guide we are covering a detailed guide on Laravel event listening and we have shared code examples there, so we expect you to hang in there till the end. Its event listening provides a good event system that allows devs to subscribe and listen to various events while they are happening within any web app. This guide will be exploring how to implement and utilize event listeners in Laravel 11. To fully comprehend the event listening scenarios we would go on to discover each aspect as we have shown below:

(I) Creating an Event

To begin, we will be creating an event. We can use the Artisan command we have shown example below

php artisan make:event UserRegistered

This commands generates a new event class in the app/Events directory. The event class might look like this

namespace App\Events;

use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserRegistered
{
    use Dispatchable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

(II) Creating a Listener

Next, we will be creating a listener for our event. We can use the following Artisan command

php artisan make:listener SendWelcomeEmail --event=UserRegistered

We would use this command for creating a new listener class now in our app/Listeners directory

namespace App\Listeners;

use App\Events\UserRegistered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendWelcomeEmail implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(UserRegistered $event)
    {
        // Logic to send welcome email
        $user = $event->user;
        // Send email to $user->email
    }
}

(III) NOW Let’s Register Our Event

We will be registering the event and listener in the EventServiceProvider

protected $listen = [
    UserRegistered::class => [
        SendWelcomeEmail::class,
    ],
];

(IV) Now Let’s Dispatch Our Listener

We can dispatch the event from anywhere in our application, typically in a controller or service class

use App\Events\UserRegistered;

public function register(Request $request)
{
    $user = User::create($request->all());

    event(new UserRegistered($user));

    return response()->json(['message' => 'User registered successfully']);
}

(V) Queued Listeners

On the other hand, YOU SHOULD ALSO KEEP in mind that some tasks may take much more time. Well, to achieve that we could always go for queuing option. See below we have shown you how to queue our listeners by using ShouldQueue interface

use Illuminate\Contracts\Queue\ShouldQueue;

class SendWelcomeEmail implements ShouldQueue
{
    // ...
}

(VI) Complex Event Handling

If you have complex tasks and codebase in your web apps, we can tell you how to handle those complex events. We have shown you example below with the Event Subscribers that has a subscriber class shown in the code example below. I think that’s great for modern web apps that we use much often in 2024.

namespace App\Listeners;

class UserEventSubscriber
{
    public function handleUserRegistration($event) {
        // Handle user registration
    }

    public function handleUserLogin($event) {
        // Handle user login
    }

    public function subscribe($events)
    {
        $events->listen(
            'App\Events\UserRegistered',
            [UserEventSubscriber::class, 'handleUserRegistration']
        );

        $events->listen(
            'App\Events\UserLoggedIn',
            [UserEventSubscriber::class, 'handleUserLogin']
        );
    }
}

Next we are going to register this subscriber in the EventServiceProvider and that’s our final code example in the dominion of event listening in Laravel 11.

protected $subscribe = [
    UserEventSubscriber::class,
];

Please leave a comment below for your curious queries that we might be able to answer or create more related contents. You should know that with using event listening in Laravel 11 we can easily perform tons of tasks to respond different scenarios in our web apps. Some of them invoke even without realizing them.