Tom Macdonald Tom Macdonald - 1 year ago 180
PHP Question

Laravel update model with unique validation rule for attribute

I have a laravel

model which has a unique validation rule on
. In my Repository, when I update the model, I revalidate the fields, so as to not have a problem with required rule validation:

public function update($id, $data) {
$user = $this->findById($id);
return $user;

This fails in testing with

ValidationException: {"username":["The username has already been taken."],"email":["The email has already been taken."]}

Is there a way of fixing this elegantly?

Answer Source

Append the currently updating id instance to the validator. You can pass the id of your instance to ignore the unique validator. In the validator use a parameter to detect if you are updating or creating it, and send the user id in the first case, then you can use:

Forcing A Unique Rule To Ignore A Given ID

'email' => 'unique:users,email_address,'.$userId

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download