F
Filament4mo ago
morty

SelectFilter unique/distinct relationship value

I have a table of tickets that belong to a location. Some locations are in the same city. How can I use a SelectFilter to get a unique list of cities from the locations table to filter the tickets? This is my code so far:
Tables\Filters\SelectFilter::make('location.city')
->label('City')
->placeholder('All')
->relationship('location', 'city')
->multiple()
->preload()
->searchable(),
Tables\Filters\SelectFilter::make('location.city')
->label('City')
->placeholder('All')
->relationship('location', 'city')
->multiple()
->preload()
->searchable(),
But this gives me a list of duplicated cities. I tried something like the following but unsuccessfully:
->relationship(
'location',
'city',
fn (Builder $query): Builder => $query->distinct())
->relationship(
'location',
'city',
fn (Builder $query): Builder => $query->distinct())
Not sure how to achieve this?
4 Replies
morty
mortyOP4mo ago
bump b2
toeknee
toeknee4mo ago
You will want to get the primary country select? then get the cities where the country is?
toeknee
toeknee4mo ago
Filament
Dependent Select Filters by Hugh Messenger - Tricks - Filament
Filament is a collection of tools for rapidly building beautiful TALL stack apps, designed for humans.
morty
mortyOP4mo ago
No sorry I'll clarify. My location table (simplified) looks like this:
| id | name | city |
|----|----------------|----------|
| 1 | Plant 1 | New York |
| 1 | Plant 2 | New York |
| 1 | Elevator | New York |
| 1 | Seed Plant 1 | Chicago |
| 2 | Seed Warehouse | Seattle |
| 2 | Bean Plant | Detroit |
| 3 | Food Plant 1 | Chicaco |
| id | name | city |
|----|----------------|----------|
| 1 | Plant 1 | New York |
| 1 | Plant 2 | New York |
| 1 | Elevator | New York |
| 1 | Seed Plant 1 | Chicago |
| 2 | Seed Warehouse | Seattle |
| 2 | Bean Plant | Detroit |
| 3 | Food Plant 1 | Chicaco |
Using the filter code in the OP, It would list New York 3 times, Chicago 2 times, etc. I just want the filter to list the unique cities, and if I filter New York, it shows the 3 locations in the table. Thinking more about this, it doesn't seem like I should use the relationship but instead just do a custom select filter. Would that be your take as well? Something like this maybe?
Tables\Filters\SelectFilter::make('location.city')
->options(
fn (): array => Location::distinct()
->orderBy('city')
->pluck('city as value', 'city as key')
->toArray()
),
Tables\Filters\SelectFilter::make('location.city')
->options(
fn (): array => Location::distinct()
->orderBy('city')
->pluck('city as value', 'city as key')
->toArray()
),
Want results from more Discord servers?
Add your server