Let's say I have the following setup. A User
has many Coments
. In my REST API I have an action /users
where I display all the users and their comments.
I would do that like this:
return Response::json(User::with('comments')->get(), 200);
But now I only want to display a User
in that list if it has at least one Comment
. Something in the lines of:
return Response::json(User::with('comments')->whereCount('users.comments', '>', 0)->get(), 200);
But that obviously does not work. What is the correct way to do this in conjunction with the with
method?
You can use in this case has
to get only users that has at least one comment:
return Response::json(User::with('comments')->has('comments')->get(), 200);