Search code examples
phplaravelvalidationlaravel-5validationrules

Laravel Forcing A Unique Rule To Ignore A Given ID not working


I am trying to ignore a unique role for a given ID but I keep getting the following error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users_email_unique' (SQL: update users set name = Name, email = [email protected], updated_at = 2018-04-06 10:01:27 where id = 1)

In my UserUpdateRequest class I have the rules set up:

public function rules()
    {
        return [
            'email' => 'required|email|unique:users,email,' . $this->route()->parameter('user'),
            'name' => 'required',
        ];
    }

$this->route()->parameter('user') gets the current model ID.

Not sure what I'm doing wrong with my rules here, anyone have any ideas?

Here is where I am making the call to the update:

public function update(Requests\UserUpdateRequest $request, $id)
    {
        $result = $this->service->update($request->except(['_token', '_method']));

        if ($result) {
            return back()->with('message', 'Successfully updated');
        }

        return back()->with('message', 'Failed to update');
    }

DB:

enter image description here


Solution

  • The problem was I was not passing the ID of the user through to the function so it was updating the current logged in user's record instead, as a result it would trigger the unique rule. You can see in the query it was doing WHERE id =1 because it was updating using Auth::id();.