How to validate two fields combined are unique
Here i need to validate the name and size_id are unique, i could do it in laravel but how could i in filamentphp. Thanks for answering
schema([
TextInput::make('name')->label('Nombre')->required(),
TextInput::make('purchase_price')->label('Precio de compra')->required()->numeric(),
TextInput::make('sale_price')->label('Precio de venta')->required()->numeric(),
TextInput::make('filled_weight')->label('Peso lleno')->required()->numeric(),
TextInput::make('empty_weight')->label('Peso vacío')->required()->numeric(),
Select::make('category_id')->relationship(name: 'category', titleAttribute: 'name')->label('Categoría')->native(false)->searchable()->preload(),
Select::make('size_id')->relationship(name: 'size', titleAttribute: 'name')->label('Tamaño')->native(false)->searchable()->preload()->required(),
Checkbox::make('sales_in_vip')->label('Se vende en el VIP')
])
5 Replies
If you need to update the record
All three combined:
same thing for size_id
Thank you for answering but it what needs to be unique is the combination of both name and size_id. Would you happen to know how to make sure their re combinedly inuque?
i got it to work like this
TextInput::make('name')->label('Nombre')->required()->rules([
fn (Get $get, string $operation, ?Model $record): Closure => function (string $attribute, $value, Closure $fail) use ($get, $operation, $record) {
if ($operation === 'create') {
$exists = Product::where('name', $get('name'))->where('size_id', $get('size_id'))->exists();
if ($exists) {
$fail('Ya existe un producto con este nombre y tamaño.');
}
}
if ($operation === 'edit') {
$exists = Product::where('name', $get('name'))
->where('size_id', $get('size_id'))
->where('id', '!=', $record->id)->exists();
if ($exists) {
$fail('Ya existe un producto con este nombre y tamaño.');
}
}
}
])
in case anybody might need itHey. Since you want the combo between the two, your approach is the way to go because I don't think that there's a rule for that.