Search code examples
laravellaravel-5laravel-5.4

How to Ignore given id during validation


Do not down vote this question, I know it has been asked before but, I couldn't find any with working answer!

I'm trying to have a unique email, but ignore a given id during validation. Tried a few methods to get this done, here is two of them which were promising yet, did not work:

Validator::make($request->all(), [
     'username' => ['username', Rule::unique('user', 'username')->ignore($user->id)]
]);

another one:

'username' => 'required|max:30,',
Rule::unique('user')->ignore($user->id),

thanks for and help.

This is some more information in case you think the aboce examples should definnetaly work. Form:

<input type="text" name="username" class="formClasses" id="usernameLocal"
 value="{{ Auth::user()->username }}">

Controller:

public function saveUserChanges(Request $request){

    $user = Auth::user();

    $this->validate($request, [
        'username' => 'required|max:30,',
        Rule::unique('user')->ignore($user->id)
    ]);

    $user->username = $request['username'];

    $user->update();

    return redirect()->route('userProfil', $user->userprofile->slug);
}

Solution

  • If you are trying to guarantee a unique email the rule will be the following:

    Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
        ],
    ]);
    

    If your field is not email in your users table then do this:

    Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users', 'column_name')->ignore($user->id),
        ],
    ]);
    

    Lastly if your unique id on the users table is not id then do:

    Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users', 'column_name')->ignore($user->id, 'unique_key_name'),
        ],
    ]);
    

    To use your code directly it would look like this:

    $this->validate($request, [
            'username' => [
                'required',
                'max:30',
                Rule::unique('users')->ignore($user->id)
            ]
        ]);
    

    The changes I made were the required and max rule need to be separated, and all of the rules needed to be in an array. I also changed the table from user to users as that is the Laravel default.

    See the docs at https://laravel.com/docs/master/validation#rule-unique