Chaining "Count Of Columns" Of A Method To Single Query Builder

- 1 answer

I have set models properly and I can use this and return as json.

$profile = Profile::with('user')->find($id);

I can also add ->with('likes') to the chain and get all the like objects. However, what I want to do is get the count of the like rows (i.e total no. of likes = total no. of rows). I know I can use a separate query with ->count(), and add it manually to the $profile variable, but what is the way of making the call in one query?

What is the way of achieve this properly?

My dummy trial:

$profile = Profile::with('user')->with(likes.count)->find($id);


You don't need to specify anything, since Laravel returns a collection of "likes" you can use the count() method, like so :

$profile = Profile::with(['user','likes'])->find($id);

More information about collections can be found in the doc