Consider a Laravel event dispatched with two listeners attached. What is the expected behavior when the event is fired?
Event::dispatch(new UserRegistered($user));
// Two listeners are registered for UserRegistered eventThink about how Laravel handles event listeners synchronously by default.
Laravel runs all listeners for an event synchronously in the order they were registered unless queued listeners are used.
Choose the correct syntax to dispatch a Laravel event named OrderShipped with an $order object.
Remember the helper function Laravel provides for dispatching events.
The event() helper function is the recommended way to dispatch events in Laravel.
Given this listener class, why might it not be triggered when the event is dispatched?
class SendWelcomeEmail implements ShouldQueue { public function handle(UserRegistered $event) { Mail::to($event->user->email)->send(new WelcomeEmail()); } } // Event dispatched as: event(new UserRegistered($user));
Think about what happens when a listener implements ShouldQueue.
Listeners implementing ShouldQueue are pushed to a queue. If no queue worker is running, the listener won't execute.
Consider this code snippet:
class CounterListener
{
public static int $count = 0;
public function handle(SomeEvent $event)
{
self::$count++;
}
}
Event::listen(SomeEvent::class, [CounterListener::class, 'handle']);
Event::dispatch(new SomeEvent());
Event::dispatch(new SomeEvent());
$count = CounterListener::$count;What is the value of $count after running this code?
Each event dispatch triggers the listener once.
The listener increments the static counter each time the event is dispatched, so after two dispatches, the count is 2.
Given an event class PaymentProcessed with a constructor requiring a $paymentId parameter, what happens if you dispatch it without arguments like event(new PaymentProcessed());?
class PaymentProcessed { public function __construct(public int $paymentId) {} }
Think about PHP constructor requirements when instantiating objects.
PHP throws a TypeError if a required constructor argument is missing when creating a new object.