V4n1ll4
V4n1ll4

Reputation: 6099

Laravel 5.1 reusing events

I have setup an event in Laravel 5.1 so that when a user is created, this event creates a user role (by creating a new row in the role_user table in the database).

I now want to setup a new event for when a user gets updated called UserUpdated. However when this new event is called, I want to reuse the listener I created for the UserCreated event which is called AssignRole.

I have copied the listener below:

<?php

namespace SimplyTimesheets\Listeners\User;

use App\Events\User\UserCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\User\UserRepoInterface;
use App\Repos\User\RoleRepoInterface;

class AssignRole
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(UserRepoInterface $user, RoleRepoInterface $role)
    {
        $this->user = $user;
        $this->role = $role;
    }

    /**
     * Handle the event.
     *
     * @param  UserCreated  $event
     * @return void
     */
    public function handle(UserCreated $event)
    {
        $user = $this->user->findUserById($event->user->id);
        $role = $this->role->findRoleById($event->request->role_id);

        return $user->roles()->save($role, ['cust_id' => $event->user->cust_id]);
    }
}

How can I reuse AssignRole in my new event handler, UserUpdated?

Upvotes: 0

Views: 220

Answers (1)

Amo
Amo

Reputation: 2944

Don't typehint the UserCreated event type. You lose a little bit of control, but it'll help you achieve what you want.

<?php

namespace SimplyTimesheets\Listeners\User;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\User\UserRepoInterface;
use App\Repos\User\RoleRepoInterface;

class AssignRole
{
/**
 * Create the event listener.
 *
 * @return void
 */
public function __construct(UserRepoInterface $user, RoleRepoInterface $role)
{
    $this->user = $user;
    $this->role = $role;
}

/**
 * Handle the event.
 *
 * @param  $event
 * @return void
 */
public function handle($event)
{
    $user = $this->user->findUserById($event->user->id);
    $role = $this->role->findRoleById($event->request->role_id);

    return $user->roles()->save($role, ['cust_id' => $event->user->cust_id]);
}
}

Then, in your EventServiceProvider, you can assign the same listener to multiple events:

   'App\Events\User\UserCreated' => [
        'App\Handlers\Events\AssignRole@handle',
    ],
    'App\Events\User\UserUpdated' => [
        'App\Handlers\Events\AssignRole@handle',
    ],

Upvotes: 1

Related Questions