Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

newbie360's avatar

Filament how to validate CheckboxList value that exists in database

Forms\Components\CheckboxList::make('regions')
    ->label(__('Regions'))
    ->gridDirection('row')
    ->relationship(
        titleAttribute: 'name',
        modifyQueryUsing: fn (Builder $query) => $query->orderBy('id'),
    )
    ->required()
    // Here, how to validate each checkbox value that exists in regions table?

Normally in Laravel is doing something like this

    public function rules(): array
    {
        return [
            'regions' => 'required|array',
            'regions.*' => 'distinct|exists:regions,id',
        ];
    }

There is nothing about validate the checkbox value in the Filament Docs: https://filamentphp.com/docs/3.x/forms/fields/checkbox-list

0 likes
4 replies
RemiM's avatar
RemiM
Best Answer
Level 16

You can probably do something like this:

use Illuminate\Validation\Rule;
...
->rules([
        'required',
        'array',
        Rule::exists('regions', 'id'),
]);
newbie360's avatar

@RemiM tired your code, and modified one of the checkbox value in browser dev tools

->rules([
    'required',
    'array',
    'exists:regions,id',
]),

i don't understand why this works without use regions.*

the field is required, is array, and the array is exists in regions ? look weird o.0

in the https://filamentphp.com/docs/3.x/forms/validation there is nothing about nested and no distinct rule

RemiM's avatar

@newbie360 I think you can add the distinct to the rules array as well.

As for why it works:

  • Filament ensures that the CheckboxList field is submitted as an array of IDs.
  • Laravel allows the exists:regions,id rule to be applied directly to an array without requiring regions.*.
  • That’s why the validation works without regions.*, as long as Filament handles the data correctly.
newbie360's avatar

@RemiM With this

Forms\Components\CheckboxList::make('regions')
    ->label(__('Regions'))
    ->relationship(
        titleAttribute: 'name,
        modifyQueryUsing: fn (Builder $query) => $query->orderBy('id'),
    )
    ->required()
    ->rules([
        'array',
        'distinct',
        'exists:regions,id',
    ]),

All Tests passed, only the distinct test fails

so it means the distinct rule is no effect, i guess Filament filtered the array before insert data to database

Please or to participate in this conversation.