Laravel

Events & Listeners

Event creation, listener registration, dispatching events, event subscribers, queued listeners, broadcast events

18 interview questionsยท
Mid-Level
1

What is an Event in Laravel?

Answer

An Event is a class that represents a significant action or occurrence that happened in the application. It serves as a data-carrying message that can be dispatched and listened to by multiple listeners in a decoupled manner. Events allow respecting the Open/Closed principle by adding behaviors without modifying existing code.

2

How to create an Event and its associated Listener with Artisan?

Answer

The command 'php artisan make:event' creates an Event, and 'php artisan make:listener' creates a Listener. By adding the --event=EventName option, the Listener is automatically typed to receive this Event. It's also possible to define the mapping in EventServiceProvider then run 'php artisan event:generate' to automatically generate all missing Events and Listeners.

3

Where to register the mapping between Events and Listeners in Laravel?

Answer

The Events-Listeners mapping is done in the $listen property of EventServiceProvider (App\Providers\EventServiceProvider). Each key is the fully qualified Event class name, and the value is an array of Listeners. Since Laravel 11, it's also possible to use auto-discovery with PHP 8 attributes #[ListensTo] to avoid manual registration.

4

How to dispatch (trigger) an Event in Laravel?

5

What is the basic structure of a Listener in Laravel?

+15 interview questions

Master Laravel for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free