Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Events and Listeners: When and How?

Premium
5 min read

Another possible option for "tasks in the background" is to call the Event in the Controller and allow different classes (current ones or future ones) to "listen" to that event.

This is the whole logic behind events/listeners: future-first thinking. You are opening the system for other developers to add their listeners in the future easily.

Imagine the scenario: you need to inform the system that the new user is registered. And then, as one of the Listeners, we want to update a Monthly Report. So first, let's make an Event class:

php artisan make:event NewUserRegistered

And a Listener:

php artisan make:listener MonthlyReportNewUserListener --event=NewUserRegistered

Now we can dispatch the Event in the Controller, similar to a job:

use App\Events\NewUserRegistered;
 
// ...
 
public function store(StoreUserRequest $request)
{
$user = (new CreateUserAction())->execute($request->validated());
NewUserDataJob::dispatch($user);
 
NewUserRegistered::dispatch($user);
//
}

Inside the Event, we won't perform any actions, but we need to accept a User, so every Listener class would have...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

J
jj15 ✓ Link copied!

There is a small typo in the "Example from Laravel Skeleton" section, at the bottom: "And you can access the User from the $event using $user->event:" it should be $event->user. 🙂

M
Modestas ✓ Link copied!

Thank you, fixed the typo!

CJ
Caleb Johnson ✓ Link copied!

I don't think the typo was addressed because I can still see it just as the user above mentioned it.

I
Interloper ✓ Link copied!

Hello, There is not Event Service provider in Laravel 11, So where should I listen like,

protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
    ],
    \Illuminate\Auth\Events\Login::class => [
        SetTenantIdInSession::class,
        RecordLogin::class,
    ],
    Logout::class => [
        ClearTenantIdFromSession::class,
    ]
];

where this will go in laravel 11.

J
jj15 ✓ Link copied!

I got an email notification of your comment, I guess since I also commented here before.

To answer your question, Laravel 11 removed all service provider files except for AppServiceProvider. You can either let your events be auto-discovered or register them manually, but in a different way, using the AppServiceProvider.

I'm sure the LD team will update this article, however, in the meantime, here's the documentation on how to register your listeners: https://laravel.com/docs/11.x/events#registering-events-and-listeners