Unique rule not working on update

Hello, I have this unique rule:
TextInput::make('item_code')
->label('Artikelcode')
->required()
->maxLength(255)
->rule(function (Get $get) {
return Rule::unique('products', 'item_code')
->where(fn ($query) => $query->where('brand_id', $get('brand_id')))
->ignore(request()->route('record'));
}),
TextInput::make('item_code')
->label('Artikelcode')
->required()
->maxLength(255)
->rule(function (Get $get) {
return Rule::unique('products', 'item_code')
->where(fn ($query) => $query->where('brand_id', $get('brand_id')))
->ignore(request()->route('record'));
}),
However when updating the record i also get the error message that it is not unique. This shouldn't be the case. How can I make this rule only validate on creating records and not on updating records?
Solution:
I figured it out. I had extra code in the creating and updating hooks off my model which interfered with the validation logic
Jump to solution
7 Replies
JJSanders
JJSandersOP5mo ago
Does anyone have an idea on this? Or has anyone dealtt with this issue before?
toeknee
toeknee5mo ago
This should work
TextInput::make('item_code')
->label('Artikelcode')
->required()
->maxLength(255)
->rule(function (Get $get, $record) {
$ref = $get('form_ref');
$rule = Rule::unique('products', 'item_code')
->where(fn ($query) => $query->where('item_code', $ref));

if ($record) {
$rule->ignore($ref, 'item_code');
}

return $rule;
})
TextInput::make('item_code')
->label('Artikelcode')
->required()
->maxLength(255)
->rule(function (Get $get, $record) {
$ref = $get('form_ref');
$rule = Rule::unique('products', 'item_code')
->where(fn ($query) => $query->where('item_code', $ref));

if ($record) {
$rule->ignore($ref, 'item_code');
}

return $rule;
})
JJSanders
JJSandersOP5mo ago
With this rule I am still able to create duplicate products when editing the form then $ref is null
Tim van Heugten
Tim van Heugten5mo ago
You want the item code to be unique across all products? Check how unique works at https://laravel.com/docs/12.x/validation#rule-unique
Validation - Laravel 12.x - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Tim van Heugten
Tim van Heugten5mo ago
When editing just feed in the current product id
Tim van Heugten
Tim van Heugten5mo ago
https://filamentphp.com/docs/3.x/forms/validation#unique is an even better read, check the ignoreRecord part in case you use the field in a panel.
Solution
JJSanders
JJSanders5mo ago
I figured it out. I had extra code in the creating and updating hooks off my model which interfered with the validation logic

Did you find this page helpful?