phplaravellaravel-filament

Filament filter on another table column


I've searched for this answer but didn't find any, so I'm here to ask. I'm using Filament 3.2 on Laravel 12. I have a RelationManager based on a table tournament_players that has a relation on players table. I have to show and filter the results of tournament_players based on the column sex in players table that has only 2 possible values: M and F. In the columns i've defined the relationship and everything works

Tables\Columns\TextColumn::make('player.sex')
                    ->label(__('Sex'))
                    ->sortable()
                    ->searchable(),

But when i get to filters I cannot make it work. That's the basic

Tables\Filters\SelectFilter::make('player.sex')
                    ->label(__('Sex'))
                    ->options([
                        'M' => __('Male'),
                        'F' => __('Female'),
                    ])
                    ->default(null),

Using it like this it's not working because the query to list results doesn't load the relation as expected. Adding the relationship like this:

->relationship('player', 'sex')

is not working also because the result is to overwrite my options with a list of M and F taken from all the players in the tournament_players table. Methods like modifyQueryUsing or getSearchResultUsing don't give better results. What I'm doing wrong?


Solution

  • After various search I found out that the solution was quite easy: it's enough to use the query method

    ->query(function (Builder $query, array $data) {
                            if (blank($data['value'])) {
                                return $query;
                            }
                            return $query->whereHas('player', function (Builder $query) use ($data) {
                                $query->where('sex', $data['value']);
                            });
                        })