hooligan hooligan - 1 month ago 5x
PHP Question

Laravel n+ issue eager loading count()

I'm going through my laravel application and trying to fix any n+ issues I can find. I have come across one scenario which isn't really an n+ but not sure what to call it.

I have 2 models Post, Comment. A post has many comments and a comment belongs to a post

When I loop through all my posts I would like to display a count of how many comments they contain. I've been able to do this fine. But the problem it is 2 queries.

How do I update the following Eloquent query to add a column for comments count.

Post::where('status', 1)->get();




As of Laravel 5.2.32, a new method was added to the query builder to help with this. When you add the withCount($relation) method to your query, it will add a {relation}_count field to the results, which contains the count of the supplied relation.

So, your query would be:

$posts = Post::where('status', 1)->withCount('comments')->get();

foreach($posts as $post) {
    echo $post->comments_count;

You can read more in the documentation here.


@JarekTkaczyk has a good blog post that does what you're looking for. Check out the article here.

Basically, you'll be creating a relationship that contains the count of comments for the post, and you'll eager load the relationship (thus avoiding the n+1). He also has some syntactic sugar in there for accessing the count through an attribute accessor.