Laravel ignore unique validation on update

1053 views laravel

I have a Model which contains many foreign keys. One of those foreign keys must be a unique value.

My validation rules are the following ones:

$data['rules'] = [
    'address' => 'required|string',
    'buyer_id' => 'required|exists:buyers,id',
    'buyer_name' => 'required|string',
    'date' => 'required|date',
    'email' => 'required|email',
    'identification_photo' => 'required|string',
    'invoice' => 'string|required',
    'middleman_id' => 'nullable|exists:middlemen,id',
    'price' => 'required|numeric|between:1,99999999999999999999999999.9999',
    'property_id' => 'required|exists:properties,id|unique:reservations,property_id',
    'purchase_receipt' => 'required|string',
    'rfc' => array(
    'tier_id' => 'nullable|exists:tiers,id',
    'user_id' => 'required|exists:users,id',

The one that I have trouble is property_id. This must be unique in the current table which is reservations.

In order to ignore that validation when I make an update, I'm adding this line of code before calling the Validator: $book['rules']['property_id'] .= ",{$item->property_id}";

And when I do a Log::info of all my rules, I got the following line: 'property_id' => 'required|exists:properties,id|unique:reservations,property_id,4',

But I keep receiving the error. Am I doing something wrong?

answered question

1 Answer


The error is on this line:

$book['rules']['property_id'] .= ",{$item->property_id}";

Instead of passing the id of the foreign key you want to ignore, you have to give the current model ID in order to ignore that validation for a specific item.

$book['rules']['property_id'] .= ",{$item->id}";

With this you tell that for your Model with id = x, ignore that specific validation.

posted this

Have an answer?


Please login first before posting an answer.