Sort Laravel Nova partition results by the count

Viewed 1674

I have a new Laravel Nova installation with a Property model. Properties have an attribute of 'country' and I want to show a partition metric on the 'country' col.

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

All works, but it only sorts alphabetically by the country which rather than descending on the count which would make more sense.

Is there any way to sort the output?

1 Answers

What you can do is :

public function calculate(Request $request)
{
    return $this->count($request, Property::orderBy('aggregate', 'desc'), 'country','country');
}

More information :
Nova will build the query as follow (nova/src/Metrics/Partition.php@aggregate):

 $results = $query->select(
            $groupBy, DB::raw("{$function}({$wrappedColumn}) as aggregate")
        )->groupBy($groupBy)->get();
  • $query is the given Builder instance of your model Property::orderBy(...) or Nova will make it for you when you pass the model Property::class
  • $function will be the method (count, min, max...)
  • $wrappedColumn will be the given column (country in your case)
  • $groupBy will be the given group by column (country) ...well you get it

At the end it will build :

$results = Property::orderBy('aggregate', 'desc')->select(
            'country', DB::raw("count(country) as aggregate")
        )->groupBy('country')->get();
Related