Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Nova metrics filtering

I have a model called Property which has an 'active' flag. I want a metric at the top of my resource which shows a count of active Properties.

My calculate method is exactly as in the doc but this shows all Properties rather than active ones:

public function calculate(Request $request)
{
    return $this->count($request, Property::class);
}

How can I add a filter?

I've tried a where clause:

public function calculate(Request $request)
{
    return $this->count($request, Property::class)->where('active','=',1);
}

And a query scope:

public function calculate(Request $request)
{
    return $this->count($request, Property::class)->active();
}

I thought I might be able to use the Nova filter I set up on the resource list page but that didn't seem to work either. I'm sure it's really easy but I haven't worked it out. Thanks for your help!

like image 906
Drewster Avatar asked Aug 27 '18 09:08

Drewster


1 Answers

Your can use every type of Eloquent\Builder instance in the $model param.

Instead of:

public function calculate(Request $request)
{
    return $this->count($request, Property::class);
}

Set a Scope on your Model

App\Property.php
...
public function scopeActive($query)
{
    return $query->where('active', 1);
}
public function scopeInactive($query)
{
    return $query->where('active', 0);
}

And use this scope as the $model param in your calculate method, because the call of the scope returns a Eloquent\Builder Instance

public function calculate(Request $request)
{
    return $this->count($request, Property::active());
    // return $this->count($request, Property::inactive());
}

Edit Of course you can make the Eloquent Builder call inline:

public function calculate(Request $request)
{
    return $this->count($request, Property::where('active', 1));
}
like image 99
Mario Avatar answered Oct 30 '22 21:10

Mario