Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dizonb's avatar

Spatie roles unique validation for multiple id during update

I created a role "Administrator" but each has one unique guard. I successfully generated them by creating custom function that replicates the web guard to sanctum. Or vice-versa depending where the role is created (e.g react frontend->sanctum guard), or laravel -> web guard).

Roles table

My current request is this:

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

I also tried this, but this won't work because it's intended only for the current role

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

It returns "The name has already been taken."

I can't update the Role because there's an existing role that have the same name. How can I make my Request to ignore the duplicate role?

0 likes
1 reply
dizonb's avatar
dizonb
OP
Best Answer
Level 1

I already got the answer from miken32 in stackoverflow

use Illuminate\Validation\Rule;

...

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

Please or to participate in this conversation.