user3574492
user3574492

Reputation: 6435

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

Upvotes: 0

Views: 1741

Answers (3)

user3574492
user3574492

Reputation: 6435

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();.

Upvotes: 0

Matthias S
Matthias S

Reputation: 3563

The error comes because you are trying to save a duplicate entry in your database. You can see that in your indexes all e-mails need to be unique. If you try to change a record to an E-Mail Address that is already used by someone else, you get the integrity constraint error message.

Upvotes: 2

Munteanu Petrisor
Munteanu Petrisor

Reputation: 491

That is a SQL error, you have a unique constraint on sql table. Probably when you made the migration you added table->string("email")->unique()

Upvotes: -1

Related Questions