Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

orest's avatar
Level 13

make query in blade view

I have the following tables

groups
- id
- title

categories
- id
- title
- parent_id
- group_id

threads 
- id 
- replies_count
- title
- category_id

replies
- id
- thread_id
  • For each group, i display the title of the group
  • For each category associated with a group, i display the title of the category, the total number of threads and replies associated with that category
  • The categories table consists of children and parent categories. Therefore, when i display the title of a parent category ( a category that has children ), i want to display next to the title, the total number of threads and replies that are associated with its children categories.

For the total number of threads for a parent category i have the following relationship and i load the count

protected $withCount = ['parentThreads']

  public function parentThreads()
    {
        return $this->hasManyThrough(
            Thread::class,
            Category::class,
            'parent_id',
            'category_id'
        );
    }

For the total number of replies associated with a group i have the following code

public function getParentRepliesCount() {
	return $this->parentThreads()->sum('replies_count');
}

The problem is that in the blade view then i have to call this accessor which makes a query ( which is a bad practice, if i'm not mistaken )

<p> {{ $category->parent_replies_count }} </p>

My question is if there is a better alternative ?

Also i'd like you ask whether it is a bad practice to have hierarchy in the same table, because currently i have a categories table which consists of parent and children, and in the Category model i end up with several methods that have parent and **children prefix **

0 likes
1 reply
orest's avatar
Level 13

i found the solution, for anyone who is interested.

The withCount can be modified and as a result it can return the sum of a column instead of the count.


$category->withCount(['parentReplies' => function($query) {
 $query->select(DB::raw('sum(replies_count)');
}

I don't quite get that how it works so if anyone has a better understanding, it will be helpful to know..

Please or to participate in this conversation.