在事件侦听器中同步多对多关系 (Laravel 5.7)

Syncing Many to many relationship in Event Listener (Laravel 5.7)

Laravel 应用程序有角色,每个 Role 都有权限(多对多)

每个用户都有多个角色(多对多)

当Role的权限为changed/updated时,事件RolePermissionsChanged被触发,监听器有如下代码:

public function handle(RolePermissionsChanged $event)
{
     $role_permissions=$event->role()->permissions;
     foreach ($event->role()->users as $user) {
        $user->permissions()->sync($role_permissions);
      }
}

这必须更新 permission_user table 才能将角色同步到用户。当事件被触发时,作业失败并出现错误:

Method Illuminate\Database\Eloquent\Collection::sync does not exist.

如果我将 foreach 循环中的行更改为 App\User::find($user->id)->permissions()->sync($role_permissions);,它可以正常工作,但我知道应该以其他方式完成。谁能指导我哪里出错了。

编辑:

下面是RolePermissionsChanged::class

<?php

namespace App\Events\Auth;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use App\Role;

class RolePermissionsChanged
{
    use Dispatchable, SerializesModels;

    public $role;

    public function __construct(Role $role)
    {
        $this->role=$role;
    }

}

$event->role() 应该是 $event->role,它是事件 class 中定义的 public 属性,其中 $event->role() 将其视为函数调用。

public function handle(RolePermissionsChanged $event)
{
    $permission_ids = $event->role->permissions->pluck('id')->toArray();

    $event->role->users->each(function (User $user) use ($permission_ids) {
        $user->permissions()->sync($permission_ids);
    });
}