F
Filamentβ€’5mo ago
ddoddsr

SelectFilter Add Null as an option

I have a select filter by manager:
SelectFilter::make('manager_id')
->options(Manager::pluck('name', 'id')->toArray())
SelectFilter::make('manager_id')
->options(Manager::pluck('name', 'id')->toArray())
How do I add a Null Only as another filter Option? Currently I am using a seperate filter for Null Only
Filter::make('null_manager')
->query(fn(Builder $query) =>
$query
->whereNull('manager_id') )
Filter::make('null_manager')
->query(fn(Builder $query) =>
$query
->whereNull('manager_id') )
How do I combine the Null Only with the manager select?
7 Replies
ddoddsr
ddoddsrOPβ€’5mo ago
Bump?
toeknee
toekneeβ€’5mo ago
Null can't apply as a select because we need the key and label, so what you can do is make a value for example 0 on the ID to have it as 'No Manager' so
SelectFilter::make('manager_id')
->options(fn () => array_merge([0 => '-- No Manager --'], User::pluck('name', 'id')->toArray()))
->query(function (Builder $query, $state) {
$value = data_get($state, 'value', null);

if ($value === '0') {
$query->whereNull('manager_id');
} elseif ($value !== null) {
$query->where('manager_id', $value);
}

return $query;
}),
SelectFilter::make('manager_id')
->options(fn () => array_merge([0 => '-- No Manager --'], User::pluck('name', 'id')->toArray()))
->query(function (Builder $query, $state) {
$value = data_get($state, 'value', null);

if ($value === '0') {
$query->whereNull('manager_id');
} elseif ($value !== null) {
$query->where('manager_id', $value);
}

return $query;
}),
Dennis Koch
Dennis Kochβ€’5mo ago
I think you are looking for placeholder() and selectablePlaceholder()
SelectFilter::make('filter')
->placeholder('Select an option')
->selectablePlaceholder()
SelectFilter::make('filter')
->placeholder('Select an option')
->selectablePlaceholder()
toeknee
toekneeβ€’5mo ago
Do you? I think null as an option as per above allows filtering where no manager is found which is very useful in some scenarios
Dennis Koch
Dennis Kochβ€’5mo ago
Oh I didn't properly read your code, because it was unreadable in the small sidebar. You are right.
ddoddsr
ddoddsrOPβ€’5mo ago
This helped me move forward, thanks THis may not be a thing but the items I'm adding should be the same type as the original items . So for a User::pluck('name', 'id')->toArray())) my added option should be numeric. + [ 0 => 'None' , -1 => Something else] I use 0 and -1 because I added two extra selections.
For another, where the id field is a string I used 'new' => "New Task" Your answer just needed a tweak to work for me. you added the [0 => "No Manager"] but use a string if ($value === '0') {`. so the query never ran Realy helpful thanks!
toeknee
toekneeβ€’5mo ago
Of course joys of mobile freehand πŸ˜…

Did you find this page helpful?