What is withCount() and withSum() in Eloquent?
Why Interviewers Ask This
This tests whether you can apply Laravel knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
withCount() adds a {relation}_count attribute to each model containing the number of related records, in a single SQL query using a subquery — no N+1. Post::withCount("comments")->get() adds $post->comments_count. Constrained count: Post::withCount(["comments" => fn($q) => $q->where("approved", true)]). withSum() adds an aggregate of a related column: Post::withSum("votes", "score")->get() adds $post->votes_sum_score. Other aggregates: withMin(), withMax(), withAvg(). These methods are far more efficient than loading the entire relationship just to get a count. Use them in list views to show "42 comments" without N+1 queries. Alias the attribute: withCount("comments as num_comments") adds $post->num_comments. Order by these attributes: Post::withCount("comments")->orderBy("comments_count", "desc")->get().
Pro Tip
This topic has Laravel-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.
Previous
What is query logging and debugging in Laravel?
Next
What is artisan queue commands in Laravel?