Events — Laravel 10 Discovery Training

The events will make it possible to better divide the operating logic of the application by emitting events when certain operations are carried out. It will then be possible to listen when these events are emitted to add logic on top.

Events

Event generation can be done using the artisan command:

php artisan make:event LoginEvent

This event will be built like a classic object and we can specify the elements necessary for its construction. Then, when desired, this event can be emitted using the method dispatch() or via the global method event()

event(new LoginEvent($user));

Listeners

Now that our events are emitted, we need to be able to listen to their triggering to add logic on top. For this, it is possible to use 2 types of classes: listeners and subscribers.

The listeners are associated with an event.

php artisan make:listener SendLoginNotification --event=LoginEvent

You will also need to modify the EventServiceProvider to associate the listener with the relevant event using the protected property $listen.

protected $listen = [
   LoginEvent::class => [
     SendLoginNotification::class,
   ],
];

Subscriber

The “subscribers” will be able to define the list of events they listen to and can also contain the actions to be performed (not necessarily).

<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Events\Dispatcher;

class UserEventSubscriber
{
    public function handleUserLogin(string $event): void {}

    public function handleUserLogout(string $event): void {}

    public function subscribe(Dispatcher $events): array
    {
        return [
            Login::class => 'handleUserLogin',
            Logout::class => 'handleUserLogout',
        ];
    }
}

Then we will modify the EventServiceProvider to add our subscriber.

protected $subscribe = [
    UserEventSubscriber::class,
];