Skip to content
Advertisement

Laravel 9 and Livewire Validation for Unique Unless Updating

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.',
    ],
);

Advertisement

Answer

'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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement