The following validation works when creating a new record, but when updating a record, partner_code
and seedgens_code
get stuck in unique
validation. How can I allow a record to be updated with the same value if it hasn't changed, but still verify uniqueness when the value changes?
$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.', ], );
P粉8212313192023-11-10 14:03:24
(1) protected $rules=[ 'partner_code' => ['required', Rule::unique('varieties')->ignore($id)] .... ] (2) protected function rules(){ 'partner_code' => ['required', Rule::unique('varieties')->ignore($id)] ... }
My adding the rule to (1) does not work I added the rule to (2) and it's working! ! !
P粉7386761862023-11-10 12:56:55
'partner_code' => 'required|unique:varieties,' . $id
or
'partner_code' => ['required', Rule::unique('varieties')->ignore($id)]
Where $id
is the ID you want to ignore.
https://laravel.com/docs/9.x/validation #RULE UNIQUE