A Beginner’s Guide to Laravel Events and Listeners
Building Robust Event-Driven Applications
Introduction
Event-driven programming has become an essential part of modern web application development. Laravel, one of the most popular PHP frameworks, provides a powerful event system that allows developers to build flexible and decoupled applications. In this tutorial, we will explore Laravel’s Events and Listeners, learning how to leverage them to create robust, scalable, and maintainable applications.

Table of Contents
Understanding Laravel Events and Listeners Setting Up Laravel and Creating Events Creating Event Listeners Registering Listeners Dispatching Events Using Event Subscribers Handling Asynchronous Events with Queues Testing Laravel Events and Listeners Conclusion References
Understanding Laravel Events and Listeners
Laravel’s event system provides a way to communicate between different components of an application in a decoupled manner. Events represent significant actions or occurrences within your application, such as a user registration, a payment confirmation, or a blog post being published. Listeners, on the other hand, define the logic that should be executed when a specific event occurs.
Setting Up Laravel and Creating Events
To get started, make sure you have Laravel installed on your machine. If not, you can install it by following the official documentation. Once you have a Laravel project set up, you can start creating events.
Events in Laravel are simple classes that reside in the `app/Events` directory by convention. You can generate a new event class using the `make:event` Artisan command. For example, to create a UserRegistered
event, run the following command:
php artisan make:event UserRegistered
This will create a new UserRegistered
event class in the app/Events
directory.
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserRegistered
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
In this class, you can define any properties or methods that are relevant to the event.
Creating Event Listeners
Next, let’s create a listener to handle the UserRegistered
event. Listeners are also simple classes and are typically stored in the app/Listeners
directory. You can generate a new listener class using the make:listener
Artisan command. For example, to create a SendWelcomeEmail
listener, run the following command:
php artisan make:listener SendWelcomeEmail --event=UserRegistered
This command will generate a SendWelcomeEmail
listener class and associate it with the UserRegistered
event.
<?php
namespace App\Listeners;
use App\Events\UserRegistered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class SendWelcomeEmail
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param \App\Events\UserRegistered $event
* @return void
*/
public function handle(UserRegistered $event)
{
//
}
}
Inside the listener class, you define the logic that should be executed when the associated event is fired. For our example, the SendWelcomeEmail
listener might send a welcome email to the newly registered user.
Registering Listeners
After creating the listener, you need to register it in Laravel’s event service provider. The service provider is responsible for binding events to their respective listeners. Open the EventServiceProvider
class located in the app/Providers
directory. In the `listen` property, you can register your events and their associated listeners.
For example:
protected $listen = [
UserRegistered::class => [
SendWelcomeEmail::class,
],
];
Here, we associate the UserRegistered
event with the SendWelcomeEmail
listener.
Dispatching Events
To trigger an event, you need to dispatch it. Dispatching an event is as simple as creating a new instance of the event class and calling the dispatch()
method on it. You can dispatch an event from anywhere in your application.
For example:
event(new UserRegistered($user));
Here, we dispatch the UserRegistered
event and pass the $user
object as a parameter.
Using Event Subscribers
Event subscribers provide a convenient way to organise multiple event listeners into a single class. Here is an example:
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Events\Dispatcher;
class UserEventSubscriber
{
/**
* Handle user login events.
*/
public function handleUserLogin(string $event): void {}
/**
* Handle user logout events.
*/
public function handleUserLogout(string $event): void {}
/**
* Register the listeners for the subscriber.
*/
public function subscribe(Dispatcher $events): void
{
$events->listen(
Login::class,
[UserEventSubscriber::class, 'handleUserLogin']
);
$events->listen(
Logout::class,
[UserEventSubscriber::class, 'handleUserLogout']
);
}
}
Inside this class, you can define the events and listeners you want to associate.
Handling Asynchronous Events with Queues
Laravel allows you to handle events asynchronously using queues. By utilising queues, you can improve performance by offloading time-consuming tasks to background workers. To enable queue handling for events, you need to configure Laravel’s queue system and specify which queues your listeners should use. To specify that a listener should be queued, add the ShouldQueue
interface to the listener class.
Testing Laravel Events and Listeners
Laravel provides a convenient testing framework for testing events and listeners. You can write tests to ensure that events are fired correctly and listeners perform the expected actions. The testing framework also supports mocking and assertions to simplify your testing process.
For example in this test we instruct Laravel to not execute the event’s listeners. We then call the logic to register a user, then assert that the
/** @test */
public function test_a_user_registration_sends_a_welcome_email(): void
{
Event::fake();
$attributes = User::factory()->raw();
$this->postJson(route('auth.register.store'), $attributes);
Event::assertDispatched(SendWelcomeEmail::class);
}
Conclusion
In this tutorial, we’ve explored Laravel’s Events and Listeners and learned how to build event-driven applications. Understanding events and listeners allows you to create decoupled and scalable systems, enhancing the flexibility and maintainability of your Laravel applications. By leveraging Laravel’s event system, you can easily incorporate event-driven programming principles into your projects.
Remember, this tutorial provides a starting point for working with Laravel events and listeners. As you dive deeper into Laravel, you’ll discover more advanced features and techniques that can further enhance your application’s functionality. Happy coding!
Resources
- Laravel Documentation: https://laravel.com/docs - Laravel Events and Listeners: https://laravel.com/docs/events