Display count of relationship in table column where pivot value = something

Hi, I need to access the many to many relationship of a model in a column and display the count of the relationship where a pivot value equals a certain value. How can I go about this? The eloquent query for this would be $model->relationship()->wherePivot('status', 'active')->count(); I just can't work out how to do this using the documentation. Or is this something I should just add to the laravel model using a getAttribute method? Thanks,
1 Reply
ChesterS
ChesterS9mo ago
There is a counts('relation') method on the columns. eg
TextColumn::make('users_count')->counts('users');
TextColumn::make('users_count')->counts('users');
But I'm not sure where it's documented or how exactly it works. If not, you can try
->getStateUsing(fn(Model $record) => $record->relationship->count())
->getStateUsing(fn(Model $record) => $record->relationship->count())
(use with('relationship') on the original query to reduce N+1 issue