Laravel App 有角色,每个Role
都有权限(多对多)
每个用户都有多个角色(多对多)
当 Role 的权限发生变化/更新时,RolePermissionsChanged
会触发 Event 并且监听器具有以下代码:
public function handle(RolePermissionsChanged $event)
{
$role_permissions=$event->role()->permissions;
foreach ($event->role()->users as $user) {
$user->permissions()->sync($role_permissions);
}
}
这必须更新permission_user
表以将角色同步给用户。触发事件时,作业失败并出现错误:
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;
}
}