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

时间:2019-01-06 08:11:06

标签: php laravel relationship eloquent--relationship

Laravel应用具有角色,每个Role都具有权限(很多)。

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

更改/更新角色的权限时,将触发事件RolePermissionsChanged,并且侦听器具有以下代码:

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;
    }

}

1 个答案:

答案 0 :(得分:1)

$event->role()应该为$event->role,这是事件类中定义的公共属性,其中$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);
    });
}