4 years ago

Get relation count as JSON response

Posted 4 years ago by berkayk

I have a Post model where has many comments via hasMany('App/Comment') relation. I am trying to return the number of comments in JSON format. The response I would like to get is like

comments: [...],
numComments: 5,

I am able to return the comments but I don't know whether there is an easy way to get number of comments with eager loading.

Post::whereIn('user_id', $ids)->with('comments')->get();


Please sign in or create an account to participate in this conversation.