Laravel Eloquent, select only rows where the relation exists Laravel Eloquent, select only rows where the relation exists laravel laravel

Laravel Eloquent, select only rows where the relation exists


According to Laravel's Eloquent documentation for querying relations (look for the "Querying Relationship Existence" subheading), this should work:

User::has('comments')->paginate(20);


Flip your thinking upside down and I think that you can do it.

$userIds = Comment::distinct()->select('user_id')->groupBy('user_id')->get();

You may not need the groupBy() but that should get you started towards a way to do it.

Then you should be able to iterate through each like so:

foreach($userIds as $id) {    $user = $id->user;  //$id is technically a Comment instance so you can                        //  call the methods on that model    echo $user->name;}


Simply like this:

User::has('comments')->with('comments')->get();