saumini/count

A Laravel Nova field.

v1.0.1 2018-11-16 16:28 UTC

This package is auto-updated.

Last update: 2024-11-28 06:04:59 UTC


README

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