Laravel using where clause on a withCount method
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Laravel's withCount() method helps in retrieving related models along with their counts by eagerly loading them without requiring extra queries. However, you might encounter issues when attempting to filter these results using a where clause on the count result. In this comprehensive blog post, we will explore various techniques to solve this issue with code examples and explanations.
Technique 1: Use Eloquent Relationships
One approach is to use Laravel's built-in relationships between models. Let's say you have a Post model that has many Upvotes (belongsToMany relationship), as shown below:php
class Post extends Model {
public function upvotes() {
return $this->belongsToMany(\App\Upvote::class);
}
}php
$posts = Post::withCount('upvotes')->whereHas('upvotes', function($query) {
$query->whereRaw('upvoteable_count > 5');
})->get();Technique 2: Leverage Raw SQL
Another option is to use Laravel's query builder to run a custom raw SQL statement that includes both the count and where clauses in the same query. Here's an example using the same Post and Upvote models and the related relationship:php
$sql = "SELECT posts.*, COUNT(upvotes.id) AS upvotes_count FROM posts LEFT JOIN upvotes ON upvotes.upvoteable_type = 'App\Post' AND upvotes.upvoteable_id = posts.id GROUP BY posts.id HAVING upvotes_count > 5";
$posts = DB::select($sql);Technique 3: Use Multiple Queries
As a last resort, you can retrieve all posts with at least one upvote and then filter those results by the count of upvotes in code:php
$posts = Post::withCount('upvotes')->get();
foreach ($posts as $post) {
if ($post->upvotes_count > 5) {
// Append filtered posts to an array or collection
}
}