0
0
Laravelframework~30 mins

Creating listeners in Laravel - Try It Yourself

Choose your learning style9 modes available
Creating Event Listeners in Laravel
📖 Scenario: You are building a Laravel application that needs to send a welcome email whenever a new user registers.
🎯 Goal: Create an event listener that listens for the UserRegistered event and triggers a welcome email to the new user.
📋 What You'll Learn
Create an event class called UserRegistered with a public property $user.
Create a listener class called SendWelcomeEmail that handles the UserRegistered event.
Register the listener in the EventServiceProvider.
Dispatch the UserRegistered event with a user instance.
💡 Why This Matters
🌍 Real World
Events and listeners help keep your Laravel app organized by separating actions triggered by events like user registration.
💼 Career
Understanding Laravel events and listeners is essential for building scalable and maintainable web applications.
Progress0 / 4 steps
1
Create the UserRegistered event class
Create an event class called UserRegistered inside app/Events with a public property $user and a constructor that accepts a $user parameter and assigns it to the property.
Laravel
Need a hint?

Use php artisan make:event UserRegistered to generate the event class, then add the $user property and constructor.

2
Create the SendWelcomeEmail listener class
Create a listener class called SendWelcomeEmail inside app/Listeners with a handle method that accepts a UserRegistered event instance.
Laravel
Need a hint?

Use php artisan make:listener SendWelcomeEmail --event=UserRegistered to generate the listener class.

3
Register the listener in EventServiceProvider
In app/Providers/EventServiceProvider.php, add the UserRegistered event and its listener SendWelcomeEmail to the $listen array.
Laravel
Need a hint?

Open EventServiceProvider.php and add the event and listener classes to the $listen array.

4
Dispatch the UserRegistered event
In your controller or service, dispatch the UserRegistered event by creating a new instance with a $user object and calling event() with it.
Laravel
Need a hint?

Use the event() helper function to dispatch the UserRegistered event with the $user instance.