Laravel Validation rules: Ignore unique doesn't is completely ignored.

Published 1 week ago by amit123

Hey, I have some trouble with the ignore unique rule.

public function rules()
{

    $user = $this->route()->parameter('user');

    //dd($user) // returns the user when updating || returns null when creating

    return [

        'name' => [

            //the ignore unique is ignored when updating

    //trying to get Trying to get property of  non-object when creating

            Rule::unique('users')->ignore($user->id, 'name'),


            //SQL Exception: Duplicate entry for PK when creating 

    // ignore unique is ignored when updating

            (isset($user) && $user)?Rule::unique('users')->ignore($user->id, 'name'):null,


            // trying to get Trying to get property of non-object when creating 

    //ignore unique is ignored when updating 

              'unique:users,name,'.$user->id.',name'

        ],

    ];

}

I tried some ways to use it, but it never work. I wrote for every way I tried what happens.

Hope you can tell me whats Wrong thanks Amit

Jaytee
Jaytee
1 week ago (101,055 XP)

Take a look at the docs here: https://laravel.com/docs/master/validation#rule-unique

You're receiving a non-object error because you're saying that the primary_key for the user model is actually name. So Laravel is looking for a name in the users table that equals the ID (number) of the user, of course, no results are found.

amit123

Forgot to tell but name is actually my PK and my table doesn't have any column 'id'. The Docs say that I have to specify 'name' as forth parameter if my PK isn't ID but still something is wrong.

Jaytee
Jaytee
6 days ago (101,055 XP)

Kinda stupid to have name as your primary key. Now you're setting yourself up for a failure when it comes to someone with the same name.

And you can plead and say that won't happen, but chances are, it will sooner or later.

But anyways, you can't use the rule unique then as it expects an ID irregardless of what the primary key is.

You could try using a closure and narrowing it down (see the docs again), but otherwise, search based on the user's id, not name.

Please sign in or create an account to participate in this conversation.