Sunday, January 2, 2022 4:05 PM

Counting Related Models In Laravel

This Laravel quick tip will allow you to count model relations whilst ensuring you don't encounter an N+1 problem.

Tips
Counting Related Models In Laravel

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.
I hope you learned something useful.
If you've made it this far, you might like to follow me on Twitter where I post similar content and connect with like-minded people.
Follow me on Twitter
Swift
List All Glyph Names For A Font In Swift
List All Glyph Names For A Font In Swift

This code snippet will show you how to print a list of all the glphys in a particular font using Swift.

Read this article
Laravel
Different Ways To Pass Data To A Laravel View
Different Ways To Pass Data To A Laravel View

Laravel views allow you to pass data to a view in a number of different ways. In this article, I'll go over four methods and describe the pros and cons for each one.

Read this article
Privacy Policy
Copyright © 2022 Carl Cassar. All Rights Reserved.