Get relation count as JSON response

Posted 3 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();

Thanks.

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

Reply to

Use Markdown with GitHub-flavored code blocks.