Bird
Raised Fist0
Laravelframework~20 mins

Event subscribers in Laravel - Practice Problems & Coding Challenges

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 Event Subscriber Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an event subscriber handles multiple events?

Consider a Laravel event subscriber class that listens to two different events. What will happen when one of those events is fired?

Laravel
class UserEventSubscriber {
    public function onUserLogin($event) {
        logger('User logged in: ' . $event->user->name);
    }

    public function onUserLogout($event) {
        logger('User logged out: ' . $event->user->name);
    }

    public function subscribe($events) {
        $events->listen(LoginEvent::class, [self::class, 'onUserLogin']);
        $events->listen(LogoutEvent::class, [self::class, 'onUserLogout']);
    }
}

// When LoginEvent is fired, what happens?
ABoth onUserLogin and onUserLogout methods are called regardless of event type.
BNo methods are called unless the subscriber is manually invoked.
COnly the onUserLogin method is called, logging the login message.
DOnly the onUserLogout method is called, ignoring the LoginEvent.
Attempts:
2 left
💡 Hint

Think about how Laravel matches events to subscriber methods.

📝 Syntax
intermediate
1:30remaining
Which code correctly registers an event subscriber in Laravel?

Choose the correct way to register an event subscriber class in Laravel's EventServiceProvider.

Laravel
class EventServiceProvider extends ServiceProvider {
    protected $subscribe = [
        // Which line is correct here?
    ];
}
A'UserEventSubscriber',
BUserEventSubscriber::class,
Cnew UserEventSubscriber(),
DUserEventSubscriber
Attempts:
2 left
💡 Hint

Look for the syntax that references the class name as a string with ::class.

🔧 Debug
advanced
2:30remaining
Why does this subscriber method not get called?

Given this subscriber method, why might it never be triggered when the event fires?

Laravel
class UserEventSubscriber {
    public function onUserRegistered($event) {
        logger('User registered: ' . $event->user->email);
    }

    public function subscribe($events) {
        $events->listen('UserRegistered', [self::class, 'onUserRegistered']);
    }
}

// Event fired as: event(new UserRegistered($user));
AThe event is fired incorrectly using event() instead of dispatch().
BThe method onUserRegistered is private and cannot be called.
CThe subscriber class is not registered in EventServiceProvider.
DThe event name string 'UserRegistered' does not match the event class name with namespace.
Attempts:
2 left
💡 Hint

Check how Laravel matches event names to classes.

❓ state_output
advanced
2:30remaining
What is the output after firing multiple events handled by one subscriber?

Given this subscriber and these events fired in order, what will be logged?

Laravel
class OrderEventSubscriber {
    public function onOrderPlaced($event) {
        logger('Order placed: ' . $event->order->id);
    }

    public function onOrderShipped($event) {
        logger('Order shipped: ' . $event->order->id);
    }

    public function subscribe($events) {
        $events->listen(OrderPlaced::class, [self::class, 'onOrderPlaced']);
        $events->listen(OrderShipped::class, [self::class, 'onOrderShipped']);
    }
}

// Events fired:
event(new OrderPlaced($order));
event(new OrderShipped($order));
ALogs 'Order placed: {id}' then 'Order shipped: {id}' in that order.
BLogs only 'Order placed: {id}' and ignores the shipped event.
CLogs only 'Order shipped: {id}' and ignores the placed event.
DNo logs appear because subscriber methods are not called automatically.
Attempts:
2 left
💡 Hint

Think about how Laravel calls subscriber methods for each event fired.

🧠 Conceptual
expert
3:00remaining
Why use event subscribers instead of individual listeners in Laravel?

Which reason best explains why you might choose an event subscriber class over separate listener classes?

ATo group related event handling methods in one class for better organization and reuse.
BBecause subscribers automatically queue events without extra setup.
CSubscribers run before middleware, unlike listeners which run after.
DSubscribers can listen to events from other applications automatically.
Attempts:
2 left
💡 Hint

Think about code organization and grouping related logic.

Practice

(1/5)
1. What is the main purpose of an event subscriber in Laravel?
easy
A. To replace middleware in routing
B. To group multiple event handlers in one class for better organization
C. To directly dispatch events to the database
D. To handle HTTP requests and responses

Solution

  1. Step 1: Understand event subscribers role

    Event subscribers group multiple event handlers in one class to keep code organized.
  2. Step 2: Compare with other options

    Options A, B, and D describe unrelated Laravel features like middleware, database dispatch, and HTTP handling.
  3. Final Answer:

    To group multiple event handlers in one class for better organization -> Option B
  4. Quick Check:

    Event subscribers organize handlers = C [OK]
Hint: Subscribers group handlers in one class for neat code [OK]
Common Mistakes:
  • Confusing subscribers with middleware
  • Thinking subscribers dispatch events
  • Mixing subscribers with HTTP controllers
2. Which method must a Laravel event subscriber class implement to register its event handlers?
easy
A. boot()
B. handle()
C. listen()
D. subscribe()

Solution

  1. Step 1: Recall subscriber method

    Laravel event subscribers use the subscribe() method to register event handlers.
  2. Step 2: Eliminate other methods

    handle() is for event listeners, listen() is used in EventServiceProvider, boot() is for service providers.
  3. Final Answer:

    subscribe() -> Option D
  4. Quick Check:

    subscribe() registers handlers = A [OK]
Hint: Subscribers use subscribe() to register handlers [OK]
Common Mistakes:
  • Using handle() instead of subscribe()
  • Confusing listen() with subscribe()
  • Thinking boot() is for subscribers
3. Given this subscriber class, what will happen when the UserRegistered event is fired?
class UserEventSubscriber {
    public function subscribe($events) {
        $events->listen('UserRegistered', [self::class, 'onUserRegistered']);
    }

    public function onUserRegistered($event) {
        echo 'User registered: ' . $event->user->name;
    }
}
medium
A. Nothing happens because subscribe is not called automatically
B. It will throw a syntax error
C. It will echo the registered user's name
D. It will echo 'User registered:' without the name

Solution

  1. Step 1: Understand event firing and subscriber listening

    The subscriber listens for 'UserRegistered' and calls onUserRegistered which echoes the user's name.
  2. Step 2: Confirm subscribe method usage

    Laravel calls subscribe() automatically when registered, so the handler runs and echoes the message with the name.
  3. Final Answer:

    It will echo the registered user's name -> Option C
  4. Quick Check:

    Event triggers echo with name = A [OK]
Hint: subscribe() auto-registers handlers; echo shows user name [OK]
Common Mistakes:
  • Thinking subscribe() must be called manually
  • Assuming syntax error due to self::class
  • Ignoring the event object passed to handler
4. Identify the error in this subscriber class:
class OrderSubscriber {
    public function subscribe($events) {
        $events->listen('OrderPlaced', 'handleOrderPlaced');
    }

    public function handleOrderPlaced($event) {
        // process order
    }
}
medium
A. The listener callback should be an array with class and method
B. The handleOrderPlaced method must be static
C. The subscribe method must return a value
D. The event name should be lowercase

Solution

  1. Step 1: Check listener callback format

    Laravel expects the listener callback as an array with class and method when used in subscribers.
  2. Step 2: Analyze given code

    The code uses a string 'handleOrderPlaced' instead of [self::class, 'handleOrderPlaced'], causing a runtime error.
  3. Final Answer:

    The listener callback should be an array with class and method -> Option A
  4. Quick Check:

    Listener callback must be array = D [OK]
Hint: Use [ClassName::class, 'method'] for subscriber callbacks [OK]
Common Mistakes:
  • Passing method name as string only
  • Thinking subscribe must return a value
  • Assuming method must be static
5. You want to create a subscriber that listens to OrderPlaced and OrderShipped events. Which is the correct way to register both handlers in the subscribe method?
hard
A. public function subscribe($events) { $events->listen('OrderPlaced', [self::class, 'handleOrderPlaced']); $events->listen('OrderShipped', [self::class, 'handleOrderShipped']); }
B. public function subscribe($events) { $events->listen(['OrderPlaced', 'OrderShipped'], [self::class, 'handleOrder']); }
C. public function subscribe($events) { $events->listen('OrderPlaced', 'handleOrderPlaced'); $events->listen('OrderShipped', 'handleOrderShipped'); }
D. public function subscribe($events) { $events->listen('OrderPlaced', self::handleOrderPlaced); $events->listen('OrderShipped', self::handleOrderShipped); }

Solution

  1. Step 1: Understand correct listener registration

    Each event must be registered separately with an array callback [Class, method].
  2. Step 2: Evaluate options

    public function subscribe($events) { $events->listen('OrderPlaced', [self::class, 'handleOrderPlaced']); $events->listen('OrderShipped', [self::class, 'handleOrderShipped']); } correctly registers both events with proper callbacks. public function subscribe($events) { $events->listen(['OrderPlaced', 'OrderShipped'], [self::class, 'handleOrder']); } wrongly groups events in one call. public function subscribe($events) { $events->listen('OrderPlaced', 'handleOrderPlaced'); $events->listen('OrderShipped', 'handleOrderShipped'); } uses strings instead of array callbacks. public function subscribe($events) { $events->listen('OrderPlaced', self::handleOrderPlaced); $events->listen('OrderShipped', self::handleOrderShipped); } uses invalid syntax without quotes.
  3. Final Answer:

    public function subscribe($events) { $events->listen('OrderPlaced', [self::class, 'handleOrderPlaced']); $events->listen('OrderShipped', [self::class, 'handleOrderShipped']); } -> Option A
  4. Quick Check:

    Separate listen calls with array callbacks = B [OK]
Hint: Register each event separately with [Class::class, 'method'] [OK]
Common Mistakes:
  • Grouping multiple events in one listen call
  • Using string method names without array
  • Using invalid syntax without quotes