Home > Software design >  Laravel 9 and Livewire Validation for Unique Unless Updating
Laravel 9 and Livewire Validation for Unique Unless Updating

Time:06-26

The below validation works when creating a new record, but when updating a record, partner_code and seedgens_code are getting caught in the unique validation. How do I allow a record to be updated with the same values if not changed, but still validate for unique when the value does change?

$this->validate(
    [
        'partner_code' => 'required|unique:varieties',
        'seedgens_code' => 'required|unique:varieties',
    ],
    [
        'partner_code.required' => 'Please add a partner code.',
        'partner_code.unique' => 'Partner code must be unique.',
        'seedgens_code.required' => 'Please add a unique partner code.',
        'seedgens_code.unique' => 'SeedGens code must be unique.',
    ],
);

CodePudding user response:

'partner_code' => 'required|unique:varieties,' . $id

or

'partner_code' => ['required', Rule::unique('varieties')->ignore($id)]

where $id is the ID that you want to ignore.

https://laravel.com/docs/9.x/validation#rule-unique

  • Related