Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
withCount with other attributes

I have a function allArticlesCount that counts all articles that have draft 1.

$allArticlesCount = Article::where('draft', 1)->count();

I also have a function that counts the number of articles in a specific category, I use withCount , but she counts absolutely all the articles, and I only need with draft 1

$categories = BlogCategory::withCount('articles')->get();

The question is, how can I make it so that all articles that have draft 1 are counted in the $categories function?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The withCount() function, like the with() function, can use an array as its argument to allow modification of the relationship being counted. In your instance, you'd do the following:

$categories = BlogCategory::withCount(['articles' => function($query){
  $query->where('draft', 1);
}])->get();

This will return your BlogCategory instances, each with a articles_count property indicative of the number of draft articles related to each instance.

Alertnatively, you can define a draftArticles relationship:

public function draftArticles() {
  return $this->hasMany(Article::class)->where('draft', 1);
  // Note: May need to adjust `hasMany()` to reference proper FK column, etc.
}

And perform withCount() on that instead:

$categories = BlogCategory::withCount('draftArticles')->get();

Each BlogCategory instance would have a draft_articles_count property reflecting that.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!