1

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?

miken32
  • 42,008
  • 16
  • 111
  • 154
dizon.ben
  • 17
  • 5

1 Answers1

0

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.

miken32
  • 42,008
  • 16
  • 111
  • 154
  • Yep it works! Thanks. My controller logic works only in updating a role without renaming it. The role with sanctum_guard still using the old role_name. But I modified my code to get the old role_name. This is to prevent the error while updating the role with sanctum guard. For example: you're going to edit the role_name "Administrator" to "Admin123". The request will find a role with sanctum guard "Admin123" which is not located in the database because the role for sanctum guard is "Administrator" and thus will result to error. Anyway, your answer solved my problem. Hats off – dizon.ben May 26 '22 at 01:56