how to filter null relationship

so i have a relationship that can be null how to let the user filter by null?
SelectFilter::make('winner')
->relationship('winner', 'name', function ($query) {
return $query->where();
})
->translateLabel()
// ⚠️ i also want to filter to draw - so my winner relationship is null. how to set that?
,
SelectFilter::make('winner')
->relationship('winner', 'name', function ($query) {
return $query->where();
})
->translateLabel()
// ⚠️ i also want to filter to draw - so my winner relationship is null. how to set that?
,
4 Replies
Filament
Filament2y ago
We're confused about what you mean by this question. Please read the #✅┊rules and reply to this message to provide more information about your use case.
ericmp
ericmpOP2y ago
in my table component i have a select filter at the moment it lets the user filter by winner. winner is a relationship. so user can choose any winner. but this relationship can be null. this means, in this case, that if is null, a draw happened so id like to add an option to that selectfilter to let the user filter by draw
Kenneth Sese
Kenneth Sese2y ago
You can use a TernaryFilter:
TernaryFilter::make('customer')
->queries(
true: fn ($query) => $query->whereHas('customer'),
false: fn ($query) => $query->whereDoesntHave('customer')
),
TernaryFilter::make('customer')
->queries(
true: fn ($query) => $query->whereHas('customer'),
false: fn ($query) => $query->whereDoesntHave('customer')
),
And you can set the true/false labels however you like
ericmp
ericmpOP2y ago
oh, nice. after some time, i finally did it this way (:
Filter::make('winner')
->form([
Forms\Components\Select::make('winner')
->options([
'eric' => 'Eric',
'bot' => 'Bot',
'draw' => 'Draw',
])
,
])
->query(function (Builder $query, array $data): Builder {
if ($data['winner'] === 'eric') {
return $query->where('winner_id', 1);
}

if ($data['winner'] === 'bot') {
return $query->where('winner_id', 2);
}

if ($data['winner'] === 'draw') {
return $query->where('winner_id', null);
}

return $query;
})
,
Filter::make('winner')
->form([
Forms\Components\Select::make('winner')
->options([
'eric' => 'Eric',
'bot' => 'Bot',
'draw' => 'Draw',
])
,
])
->query(function (Builder $query, array $data): Builder {
if ($data['winner'] === 'eric') {
return $query->where('winner_id', 1);
}

if ($data['winner'] === 'bot') {
return $query->where('winner_id', 2);
}

if ($data['winner'] === 'draw') {
return $query->where('winner_id', null);
}

return $query;
})
,
what do u think?
Want results from more Discord servers?
Add your server