Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Tim MacDonald:
Loading Eloquent relationship counts
Nov 12, 2018 @ 15:51:30

Tim MacDonald has a new post to his site sharing methods that the Laravel Eloquent users (either in the framework or outside of it) can use to load in the counts of relationships without having to fetch the entire relationship data set.

It is often useful to show the number of related models a given instance has, but not actually need any specific information about the related models, just how many exist. In this scenario you do not want to load all of the related models into memory to count them, we want our database to do the heavy lifting for us. Laravel offers a number of ways to retrieve relationship counts. 2 have been around for a while, but there is a new kid on the block.

He looks at three methods you can use to get these counts: via the query builder manually, directly on the relationship and, more recently added, from an eloquent collection. He goes through each of these methods, providing a summary of the technique and code examples showing how it's implemented.

tagged: laravel eloquent relationship count tutorial querybuilder collection

Link: https://timacdonald.me/loading-eloquent-relationship-counts/


Trending Topics: