Monday, March 13, 2017

One event to multiple handlers - laravel

I want to log when some client has been created/updated/deleted with events. Is this possible without creating Events for all actions? I'm using the latest version of laravel (5.4 atm)

Event:

class EventClient
{
    use SerializesModels;
    public $client;
    public function __construct(Client $client)
    {
        $this->client = $client;
    }
}

Handler:

public function onCreateClient(EventClient $event) { //log }

public function onUpdateClient(EventClient $event) { //log }

public function subscribe($events)
{
    $events->listen(
        'App\Events\EventClient',
        'App\Listeners\HandleClient@onCreateClient'
    );

    $events->listen(
        'App\Events\EventClient',
        'App\Listeners\HandleClient@onUpdateClient'
    );
}

On model i used the default protected $events:

protected $events = [
       'created' => EventClient::class,
       'updated' => EventClient::class,
   ];

EventServiceProvider i used subscribers

protected $subscribe = [
   'App\Listeners\HandleClient',
 ];

When i create/update some client it log twice, obviously he runs the created and updated event because he uses the same Event (EventClient).

What am i missing? It is possible to don't create multiple events to achieve this?



via JoseSilva

Advertisement