nsaumini / nova-field-count by nsaumini

A Laravel Nova field.
425,429
29
2
Package Data
Maintainer Username: nsaumini
Package Create Date: 2018-11-14
Package Last Update: 2019-04-27
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-11-20 03:00:13
Package Statistics
Total Downloads: 425,429
Monthly Downloads: 5,455
Daily Downloads: 302
Total Stars: 29
Total Watchers: 2
Total Forks: 7
Total Open Issues: 2

Nova Field Count

A Laravel Nova field for relationship count. Displays only on index view.

Installation

> composer require saumini/count

Usage

Define the relationship on model.

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Use Count field on relationship.

use Saumini\Count\RelationshipCount;

class Survey extends Resource
{
    ...
    public function fields(Request $request)
    {
        return [
            RelationshipCount::make('Comments Count', 'comments'),
        ];
    }
}

For sortable field

use Saumini\Count\RelationshipCount;

class Survey extends Resource
{
    ...
    public function fields(Request $request)
    {
        return [
            RelationshipCount::make('Comments Count', 'comments')->sortable(),
        ];
    }
    
    // Overwrite the indexQuery to include relationship count
    public static function indexQuery(NovaRequest $request, $query)
    {
        // Give relationship name as alias else Laravel will name it as comments_count
        return $query->withCount('comments as comments');
    }
}

Screenshot

Screenshot 1