0
0
Laravelframework~30 mins

Event dispatching in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Laravel Event Dispatching Basics
📖 Scenario: You are building a simple Laravel application that needs to notify when a new user registers. You will use Laravel's event dispatching system to handle this notification.
🎯 Goal: Create a Laravel event and listener to dispatch a UserRegistered event when a new user is created, and handle it by logging a message.
📋 What You'll Learn
Create an event class named UserRegistered with a public property user.
Create a listener class named SendWelcomeEmail that accepts the UserRegistered event.
Dispatch the UserRegistered event after creating a new user instance.
Register the event and listener in the EventServiceProvider.
💡 Why This Matters
🌍 Real World
Event dispatching in Laravel helps separate concerns by letting you trigger actions when something important happens, like user registration, without mixing code.
💼 Career
Understanding Laravel events and listeners is essential for building scalable and maintainable web applications, a common requirement for Laravel developer roles.
Progress0 / 4 steps
1
Create the UserRegistered event class
Create a Laravel event class named UserRegistered in the app/Events directory. It should have a public property called user and a constructor that accepts a $user parameter and assigns it to the property.
Laravel
Need a hint?

Remember to add the __construct method and assign the $user parameter to the public property user.

2
Create the SendWelcomeEmail listener class
Create a Laravel listener class named SendWelcomeEmail in the app/Listeners directory. It should have a handle method that accepts a UserRegistered event instance as a parameter.
Laravel
Need a hint?

Define the handle method with a parameter typed as UserRegistered.

3
Dispatch the UserRegistered event after user creation
In a controller or service, after creating a new user instance stored in the variable $user, dispatch the UserRegistered event by passing $user to it.
Laravel
Need a hint?

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

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

Map the event class to the listener class inside the $listen array.