Events and Listeners

📘 Laravel 👁 38 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Events and listeners in Laravel provide a clean and flexible way to implement the Observer pattern. They allow your application to react to actions or changes (events) by executing separate pieces of logic (listeners), helping keep your code modular and maintainable.


1. What Are Events?

An event represents something that has happened in your application.

Examples:

  • A user has registered

  • An order has been placed

  • A file has been uploaded

Events are stored in:

app/Events

2. What Are Listeners?

A listener responds to an event and performs a specific action.

Examples:

  • Send a welcome email

  • Log activity

  • Update user statistics

Listeners are stored in:

app/Listeners

3. Why Use Events and Listeners?

Benefits:

  • Loose coupling between components

  • Cleaner and more organized code

  • Easier testing and maintenance

  • Supports multiple actions for a single event


4. Creating Events and Listeners

Create an event:

php artisan make:event UserRegistered

Create a listener:

php artisan make:listener SendWelcomeEmail --event=UserRegistered

5. Event Structure

Example event:

class UserRegistered { public $user; public function __construct($user) { $this->user = $user; } }

6. Listener Structure

Example listener:

class SendWelcomeEmail { public function handle(UserRegistered $event) { // Send email to $event->user } }

7. Registering Events and Listeners

Events are registered in:

app/Providers/EventServiceProvider.php

Example:

protected $listen = [ UserRegistered::class => [ SendWelcomeEmail::class, ], ];

8. Dispatching Events

Dispatch an event using:

event(new UserRegistered($user));

Or:

UserRegistered::dispatch($user);

9. Queued Listeners

Listeners can run in the background by implementing ShouldQueue:

class SendWelcomeEmail implements ShouldQueue { public function handle(UserRegistered $event) { // } }

10. Event Subscribers

Subscribers group multiple listeners in one class.

Create subscriber:

php artisan make:listener UserEventSubscriber

Example:

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

Register in EventServiceProvider.


11. Built-in Laravel Events

Laravel provides built-in events such as:

  • Registered

  • Login

  • Logout

  • Failed

  • Verified

These can be used for authentication-related actions.


Conclusion

Events and listeners in Laravel help build scalable and well-structured applications by separating core logic from side effects. They enable developers to respond to application activities efficiently while keeping code clean, flexible, and easy to maintain.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes