Laravel - Event Handling
Laravel’s event handling system allows you to subscribe to and listen to events in your application, enabling decoupled and flexible architecture. Events are useful for sending notifications, logging activities, broadcasting, and more.
Step 1: Events and Listeners
Laravel’s event system consists of:
- Events: Represent an action that has occurred in the application.
- Listeners: Handle the event and execute logic when it is triggered.
For example, when a user registers, an event like UserRegistered
is fired, and a listener SendWelcomeEmail
sends an email.
Step 2: Creating Events and Listeners
Laravel provides an artisan command to generate events and listeners.
1. Generate an Event
Run the following command to create an event:
This creates a file in app/Events/UserRegistered.php
:
This event is triggered when a user registers.
2. Generate a Listener
Run the command:
This creates app/Listeners/SendWelcomeEmail.php
:
ShouldQueue
: Makes the listener execute asynchronously.handle()
: Defines the action when the event occurs.
Step 3: Register Events and Listeners
Laravel automatically discovers events and listeners, but you can manually register them in:
File: app/Providers/EventServiceProvider.php
Run the following command to cache the events and listeners:
Step 4: Firing an Event
To trigger the event, use:
Alternatively, you can use the dispatch()
method:
Step 5: Using Event Subscribers (Optional)
Subscribers handle multiple events in a single class.
1. Create a Subscriber
Run:
Modify app/Listeners/UserEventSubscriber.php
:
2. Register the Subscriber
In EventServiceProvider.php
:
Step 6: Testing the Event System
Use the artisan command to test:
Then dispatch the event:
Check if the listener executes properly.
Conclusion
✅ Laravel’s event system helps decouple logic.
✅ Events can be queued for better performance.
✅ Auto-discovery simplifies event-listener management.
✅ Useful for sending notifications, logging, broadcasting, etc.
Would you like an example of real-time broadcasting using WebSockets? 🚀