Counting Related Models In Laravel

1 year ago Sun, Jan 2, 2022

Very often when retrieving a model in Laravel, it is useful to load a count of related models at the same time. For example, when loading a blog post, you might want to display the number of comments left on that post.

Luckily, Laravel has a method to do just that:

$posts = Post::withCount('comments')->get();

What's more, as of Laravel 8, you can also make use of the withMin, withMax, withAvg, withSum, and withExists methods.

Read more in the Laravel Documentation.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.