F
Filament5mo ago
Jefry

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
Bruno Pereira
Bruno Pereira5mo ago
TextInput::make('name')->label('Nombre')->required()->unique(table: Model::class, column: 'column_name')
TextInput::make('name')->label('Nombre')->required()->unique(table: Model::class, column: 'column_name')
If you need to update the record
TextInput::make('name')->label('Nombre')->required()->unique(table: Model::class, column: 'column_name',ignoreRecord: true)
TextInput::make('name')->label('Nombre')->required()->unique(table: Model::class, column: 'column_name',ignoreRecord: true)
All three combined:
TextInput::make('name')->label('Nombre')->required()->unique(table: YourModel::class, column:'column_name',ignoreRecord: true)
TextInput::make('name')->label('Nombre')->required()->unique(table: YourModel::class, column:'column_name',ignoreRecord: true)
same thing for size_id
Jefry
JefryOP5mo ago
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?
Jefry
JefryOP5mo ago
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 it
Bruno Pereira
Bruno Pereira5mo ago
Hey. 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.
Want results from more Discord servers?
Add your server