michael1986's avatar

Make a relation count field sortable in Nova

Hi all,

I'd like to know if it's possible to make a relation count field sortable in Nova.

Number::make(__('Categories'), function () {
    return $this->categories->count();
}),

Obviously adding ->sortable() doesn't work here.

0 likes
8 replies
anderly's avatar
anderly
Best Answer
Level 3

Best way to do this is include your count on the model (possibly with a global scope).

Example:

static::addGlobalScope('with-category-count', function (Builder $builder) {
        $builder->withCount('categories');
});

Then, in your Nova Resource:

Number::make(__('Categories'), 'categories_count')
                ->sortable(),
4 likes
domthomas-dev's avatar

Hi @anderly

I think you can't use sortable method.

And, you can use $withCount attribute

class Product extends Model
{

    protected $withCount = ['categories'];
}
1 like
MannikJ's avatar

This doesn't seem to work, because Nova automatically adds the table prefix to the column name.

mindfullsilence's avatar

You can do this in your resource by defining your indexQuery method.

<?php

namespace App\Nova;

use Laravel\Nova\Http\Requests\NovaRequest;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Number;

class Product extends Resource {

    public static function indexQuery(NovaRequest $request, $query) {
        // adds a `tags_count` column to the query result based on 
        // number of tags associated with this product
        return $query->withCount('tags'); 
    }

    public function fields(Request $request) {
        return [
            Number::make('# Of Tags', 'tags_count')
                ->onlyOnIndex()
                ->sortable(),
        ];
    }

}
16 likes
clem's avatar

@pasilyo it's indeed the best solution.

It's such a common need that I think it should be built into Nova.

Please or to participate in this conversation.