Laravel 5 验证多对多数据

Laravel 5 Validate many to many data

创建新的 Role 时,管理员可以 select 他想分配给该角色的不同权限。将新创建的 Role 保存到数据库后,selected 权限将同步到 right_role table.

public function store(CreateRoleRequest $request) {
    $role = new Role(['name' => $request->get('name')]);

    $rights = [];
    foreach ($request->get('rights') as $id => $enabled) {
        if ($enabled) {
            $rights[] = $id;
        }
    }

    $role->save();
    $role->rights()->sync($rights);

    return redirect()->route('users.index');
}

但是我如何根据不存在的值验证提交的权限?我可以在 CreateRoleRequest 内执行此操作吗?

这可以通过自定义验证器来完成。下面是如何在 CreateRoleRequest

中使用自定义验证器的示例
public function __construct() {
    Validator::extend("valid_rights", function($attribute, $value, $parameters) {
        $rules = [
            'right_id' => 'exists:rights,id'
        ];
        foreach ($value as $rightId) {
                $data = [
                    'right_id' => $rightId
                ];
                $validator = Validator::make($data, $rules);
                if ($validator->fails()) {
                    return false;
                }
            }
        return true;
    });
}

public function rules() {
    return [
        'containers' => 'required|valid_rights',
    ];
}