Courses

How to Structure Laravel 11 Projects

Events and Listeners: When and How?

Summary of this lesson:
- Setting up Event classes
- Creating Event Listeners
- Implementing event dispatching
- Managing event-driven operations

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 11 lessons of this course? (56 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord