Bird
Raised Fist0
Laravelframework~20 mins

Creating listeners in Laravel - Practice Exercises

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Laravel Listener Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a Laravel event listener is triggered?
Consider a Laravel event listener that listens to a UserRegistered event. What is the expected behavior when the event is fired?
Laravel
class SendWelcomeEmail {
    public function handle(UserRegistered $event) {
        Mail::to($event->user->email)->send(new WelcomeEmail());
    }
}

// Event fired somewhere in the app
event(new UserRegistered($user));
AThe listener logs the user out immediately.
BThe listener updates the user's password automatically.
CThe listener deletes the user from the database.
DThe listener sends a welcome email to the registered user's email address.
Attempts:
2 left
💡 Hint
Think about what the listener's handle method is doing with the event data.
📝 Syntax
intermediate
2:00remaining
Which code correctly registers a listener in Laravel's EventServiceProvider?
You want to register a listener named SendWelcomeEmail for the UserRegistered event. Which code snippet correctly does this in the EventServiceProvider?
A
protected $listen = [
    'UserRegistered' => 'SendWelcomeEmail',
];
B
protected $listen = [
    UserRegistered::class => [
        SendWelcomeEmail::class,
    ],
];
C
protected $listen = [
    SendWelcomeEmail::class => UserRegistered::class,
];
D
protected $listeners = [
    UserRegistered => SendWelcomeEmail,
];
Attempts:
2 left
💡 Hint
Check the property name and the array structure for event to listeners mapping.
🔧 Debug
advanced
2:00remaining
Why does this Laravel listener not respond to the event?
Given this listener code, why does it not respond when the event is fired? class LogUserLogin { public function handle(UserLoggedIn $event) { Log::info('User logged in: ' . $event->user->id); } } // EventServiceProvider protected $listen = [ UserLogin::class => [LogUserLogin::class], ];
AThe listener class does not have a constructor, so it won't be called.
BThe handle method should be named onUserLoggedIn to work properly.
CThe event class name in the $listen array is incorrect; it should be UserLoggedIn::class, not UserLogin::class.
DThe Log facade is not imported, causing a fatal error.
Attempts:
2 left
💡 Hint
Check the event class names used in the listener and the provider.
❓ state_output
advanced
2:00remaining
What is the output when multiple listeners modify the same event data?
Consider an event OrderPlaced with a property $order->status initially 'pending'. Two listeners modify this status: Listener1: sets status to 'processing' Listener2: sets status to 'completed' If both listeners are registered and the event is fired, what will be the final status of the order?
A'completed', because the last listener to run overwrites the status.
B'processing', because the first listener sets the status and it cannot be changed.
C'pending', because event data is immutable and cannot be changed by listeners.
DAn error occurs because two listeners modify the same property.
Attempts:
2 left
💡 Hint
Think about how listeners run and modify shared event data.
🧠 Conceptual
expert
2:00remaining
Which statement about Laravel event listeners is true?
Select the correct statement about Laravel event listeners.
AListeners can be queued to run asynchronously by implementing the ShouldQueue interface.
BListeners must always be registered manually in the EventServiceProvider to work.
CListeners cannot access the event data passed to them.
DListeners automatically retry on failure without any configuration.
Attempts:
2 left
💡 Hint
Think about how Laravel handles long-running or delayed listener tasks.

Practice

(1/5)
1. What is the main purpose of creating listeners in Laravel?
easy
A. To define database migrations
B. To respond automatically when specific events happen
C. To create routes for web requests
D. To handle user authentication manually

Solution

  1. Step 1: Understand what listeners do

    Listeners are designed to respond automatically when events occur in the application.
  2. Step 2: Compare with other options

    Options B, C, and D relate to migrations, routing, and authentication, which are not the main purpose of listeners.
  3. Final Answer:

    To respond automatically when specific events happen -> Option B
  4. Quick Check:

    Listeners respond to events = A [OK]
Hint: Listeners react to events automatically in Laravel [OK]
Common Mistakes:
  • Confusing listeners with routes or migrations
  • Thinking listeners handle authentication directly
  • Believing listeners are manually triggered
2. Which of the following is the correct artisan command to create a listener named UserRegisteredListener?
easy
A. php artisan create:listener UserRegisteredListener
B. php artisan make:event UserRegisteredListener
C. php artisan listener:create UserRegisteredListener
D. php artisan make:listener UserRegisteredListener

Solution

  1. Step 1: Recall the artisan command for listeners

    The correct command to create a listener is php artisan make:listener ListenerName.
  2. Step 2: Check other options

    Options A and C use incorrect command formats, and D creates an event, not a listener.
  3. Final Answer:

    php artisan make:listener UserRegisteredListener -> Option D
  4. Quick Check:

    Use make:listener to create listeners [OK]
Hint: Use 'make:listener' to create listeners with artisan [OK]
Common Mistakes:
  • Using 'create:listener' instead of 'make:listener'
  • Confusing listener creation with event creation
  • Typing commands in wrong order
3. Given this listener code snippet, what will be the output when the event triggers?
public function handle(UserRegistered $event) {
    echo 'Welcome, ' . $event->user->name . '!';
}
medium
A. It does nothing because echo is not allowed in listeners
B. It throws an error because $event is undefined
C. It prints 'Welcome, ' followed by the user's name
D. It prints 'Welcome, User!' regardless of the actual name

Solution

  1. Step 1: Understand the handle method

    The handle method receives the event object, here UserRegistered, which contains the user data.
  2. Step 2: Analyze the echo statement

    It prints 'Welcome, ' plus the user's name from the event object, so the output is personalized.
  3. Final Answer:

    It prints 'Welcome, ' followed by the user's name -> Option C
  4. Quick Check:

    handle() prints welcome message with user name [OK]
Hint: handle() uses event data to customize output [OK]
Common Mistakes:
  • Assuming $event is not passed automatically
  • Thinking echo is disallowed in listeners
  • Ignoring the user property inside the event
4. Identify the error in this listener class code:
class SendNotification {
    public function handle() {
        // send notification code
    }
}
medium
A. The handle method must accept the event object as a parameter
B. The class name must end with 'Listener'
C. The handle method should be static
D. Listeners cannot send notifications

Solution

  1. Step 1: Check handle method signature

    The handle method must accept the event object parameter to receive event data.
  2. Step 2: Verify other options

    Class name ending with 'Listener' is a convention but not required; handle should not be static; listeners can send notifications.
  3. Final Answer:

    The handle method must accept the event object as a parameter -> Option A
  4. Quick Check:

    handle(event) needs event parameter [OK]
Hint: handle() always needs event parameter [OK]
Common Mistakes:
  • Omitting event parameter in handle method
  • Thinking class name must have 'Listener' suffix
  • Making handle method static incorrectly
5. You want to create a listener that logs a message only when a user registers and their email ends with '@example.com'. How should you modify the listener's handle method to achieve this?
hard
A. Add an if condition inside handle to check $event->user->email ends with '@example.com' before logging
B. Create a separate listener for '@example.com' emails and register it separately
C. Modify the event to only fire for '@example.com' emails
D. Use middleware to filter events before listeners run

Solution

  1. Step 1: Understand listener filtering

    Listeners receive all events they listen to; filtering specific cases is done inside the handle method.
  2. Step 2: Apply condition inside handle

    Check if the user's email ends with '@example.com' using an if statement before running the logging code.
  3. Step 3: Evaluate other options

    Creating separate listeners or modifying events is more complex; middleware does not filter events.
  4. Final Answer:

    Add an if condition inside handle to check $event->user->email ends with '@example.com' before logging -> Option A
  5. Quick Check:

    Filter event data inside handle() with if condition [OK]
Hint: Filter event data inside handle() using if condition [OK]
Common Mistakes:
  • Trying to filter events outside listener handle method
  • Assuming middleware filters events
  • Creating unnecessary multiple listeners