Laravel Filament handle relationship data before saving

2.3k views Asked by At

I have a question: in a Filament Form I have a manyToMany relationship rendered with a Checkboxlist. Before the db saving, I have to perform some "actions" with the values inside the list.

Possible that there is no way to handle that values?

I looked in the methods mutateFormDataBeforeSave or handleRecordCreation but the $data variable contains all the form data except the relationship one.

1

There are 1 answers

0
n0nsensei On

If anyone still needs it, you can use the saveRelationshipsUsing() method in ChecboxList field, and you can inject your required utilities accordingly. Injecting $state will give you an array of the checked model Ids. Below is a snippet I use in my project.

CheckboxList::make('categories')
                 ->relationship(
                    'categories',
                     titleAttribute: 'name',
                 )
                 ->saveRelationshipsUsing(function (Model $record, $state){
                        //your code here
                        //eg: $record->categories()->sync($state)  for manyToMany default behaviour
                 })

Here, $model gives the resource model, and state gives the selected categories ids like [1,3,4]