Skip to content
Advertisement

Laravel 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

IMAGE Here

My current request validation rule 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?

Advertisement

Answer

The unique rule has been updated to be more flexible in modern versions of Laravel.

You can define your validation rule like this:

use IlluminateValidationRule;

...

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

Additional where clauses were previously added with more parameters in the unique: comma-separated list (and still can be AFAIK) but it was very hard to tell at a glance what the validation was doing.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement