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
?