I have a Laravel Nova resource, and it has a computed value inside it entitled views. I want to add a Nova filter which can affect the result of the computed value (not the query itself), but can't figure out how to do this.
My computed value looks like this:
Text::make('Views', function() {
return $this->getViewsCount();
}),
I want to be able to do something like:
Text::make('Views', function() {
if(isset($filterValue)) {
return $this->getViewsBetween($filterValue);
} else {
return $this->getViewsCount();
}
}
You can try to get the filters value from the request:
$queryFilters = $request->query('filters')
The parameter is base64 and json encoded so you'll have to decode it first.
Take a look at Laravel\Nova\Http\Requests\DecodesFilters
as reference.
Your computed field could look something like this:
Text::make('Views', function () use ($request) {
$queryFilters = $request->query('filters');
$decodedFilters = collect(json_decode(base64_decode($queryFilters), true));
$computed = $decodedFilters->map(function ($filter) {
return $this->getViewsBetween($filter['value']);
});
if ($computed->isEmpty()) {
return $this->getViewsCount();
}
return $computed->implode(',');
})
Update: $decodedFilters
holds the class and the value for the selected filters.
Illuminate\Support\Collection {
#items: array:1 [
0 => array:2 [
"class" => "App\Nova\Filters\UserType"
"value" => "admin"
]
]
}