Laravel spatie 角色在更新期间对多个 id 进行唯一验证

Laravel spatie roles unique validation for multiple id during update

我创建了一个“管理员”角色,但每个角色都有一个独特的守卫。我通过创建将网络防护复制到 sanctum 的自定义函数成功生成了它们。或者 vice-versa 取决于创建角色的位置(例如 react frontend->sanctum guard),或者 laravel -> web guard)。


角色 table

我当前的请求验证规则是这样的:

    'name' => ['required', 'max:70', 'unique:roles,name,'. $this->role->id]

我也试过了,但这行不通,因为它只适用于当前角色

    'name' => ['required', 'max:70', 'unique:roles,name,id']

It returns "The name has already been taken."

我无法更新角色,因为存在同名的现有角色。我怎样才能让我的请求忽略重复的角色?

unique 规则在 Laravel 的现代版本中已 updated to be more flexible

您可以这样定义验证规则:

use Illuminate\Validation\Rule;

...

$rules = [
    "name" => [
        "required",
        "max:70",
        Rule::unique("roles")
            ->ignore($this->role->id)
            ->where("guard_name", $this->role->guard_name)
    ],
];

以前在 unique: comma-separated 列表中添加了带有更多参数的其他 where 子句(并且仍然可以是 AFAIK),但很难一眼看出验证在做什么。