Laravel Events and Listeners – A Complete Guide 2024

Laravel Events offer an easy-to-use implementation of the Observer Design Pattern, which enables you to subscribe to and track different events that take place within your application. These events are usually defined as classes and stored in the app/Events directory, while their corresponding listeners are kept in app/Listeners.

One of the significant benefits of using the Observer pattern is that it helps you to compartmentalize different functions within your application. For instance, a single event can have multiple independent listeners. To illustrate, suppose you want to receive an alert every time a new user signs up on your website. Instead of modifying the User Registration class or extending it, you can create an independent event listener class called “Registration” and subscribe it to the relevant event. This listener class can then handle the notification logic, keeping it separate from the registration logic.

What is an Event?

Laravel Events provide a mechanism to monitor the activities of an application, such as login and registration. By creating an event class, you can observe specific activities and perform related functions when they occur. For instance, a login event class can monitor user login activity and perform certain functions accordingly.

What is a Listener?

A Listener is a class that listens to the events they are associated with and performs a task, that is, they perform a given task for the event.

Laravel Event Listeners are classes that perform a specific task when an associated event is triggered. For example, a welcome email can be sent to a newly registered user, and a role can be assigned based on the user’s registration information. Instead of adding these tasks to the RegisterController, which would violate the Single Responsibility Principle(SOLID), they can be performed by separate listeners that respond to the event. This keeps each component focused on its designated task and improves the application’s maintainability.

Creating Event and Listener Class

To create an event class, use the artisan command make:event

php artisan make:event Register

This command will create a new class in your application’s app\Events folder, and that’s all you need to create an event class.

To create a listener class, use the artisan command make:listener

php artisan make:listener SendWelcomeEmail

This command, just like creating an event, will create a new class in your application’s app\Listeners folder, which is all you need to create a listener class.

Registering Event and Listener Class

In order for our events and listeners to work, we must register them in the App\Providers\EventServiceProvider class, which was already set up for us during the installation of our Laravel project.

Looking into the App\Providers\EventServiceProvider class you will see the $listen array in which we will register our events and listeners.

namespace App\Providers;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Register::class => [
            SendWelcomeEmail::class,
        ],
    ];
}

Let’s take a look at our Register event and pass our new user into it.

<?php
 
namespace App\Events;
 
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
 
class Register
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
 
    /**
     * The order instance.
     *
     * @var \App\Models\User
     */
    public $user;
 
    /**
     * Create a new event instance.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

And now let’s look at our listener SendWelcomeEmail where all the logic of sending email will be

<?php
 
namespace App\Listeners;
 
use App\Events\Register;
 
class SendWelcomeEmail
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Handle the event.
     *
     * @param  \App\Events\Register  $event
     * @return void
     */
    public function handle(Register $event)
    {
        // Access the user using $event->user...
        // email sending logic for $event->user->email
    }
}

Dispatching an Event

At the time of writing this article, I was aware of two methods for dispatching events and triggering listeners:

  • event(new EventClass()); // event(new Register($user));
  • EventClass::dispatch(); // Register::dispatch($user);

You should note that public properties declared on the event class can be accessed on the listener class that is associated with it.

Leave a Comment