user6658395
user6658395

Reputation: 31

Automatically get "withCount"

I know that you can automatically retrieve relationships by putting the following in a model class:

protected $with = [
    'users', 'scores'
];

But is it possible to do the same with "withCount"?

I tried this but it didn't work:

protected $withCount = [
    'users'
];

Upvotes: 2

Views: 1343

Answers (2)

Zeeshan Haider
Zeeshan Haider

Reputation: 41

In Model class you can add global scope in booted function you can call any Model relation in global scope using withCount().

protected static function booted()
{
    parent::booted();

    static::addGlobalScope(
        'computedColumns',
        static fn(Builder $query) => $query
            ->withCount('relation as relation_count')
    );
}

you can access it on your model instance using "$model->relation_count"

$model = Model::find($id);
$model->relation_count;

Upvotes: 1

Michael Chan
Michael Chan

Reputation: 41

If you want to have the count number of a related model included in the array form output, you have to first create an accessor and put it in the $appends array of the model.


  1. Define the accessor

    //  In your model
    public function getUserCountAttribute() {
        $users = $this->users;    //  From the relationship you defined
        return $users->count();
    }
    

    You can now use userCount attribute in your object.


  1. Add the userCount attribute to the $appends array in the model class

    //  In your model
    protected $appends = ['userCount'];
    

Upvotes: 2

Related Questions