Home > Net >  Laravel spatie roles unique validation for multiple id during update
Laravel spatie roles unique validation for multiple id during update

Time:05-26

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?

CodePudding user response:

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

You can define your validation rule like this:

use Illuminate\Validation\Rule;

...

$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.

  • Related