Q:

Recursive Relation Roles Laravel 5.6

I just don't know how to query this things... I work in the collection but it's very awful code. 
// user with roles
$user = User::where('id', Auth::User()->id)
    ->with('roles')
    ->first();

// Get the RoleParentId
$roleParentId = collect($user->roles)->min('parent_id');

// Get the all the children of the role parent Id with it's children and users
$role = \App\Model\Role::where('parent_id', $roleParentId)
    ->with('allChildren.users')
    ->first();

// Loop to get the Collection of children users
$childrenUsers = collect();
foreach($role->allChildren as $children){
    $childrenUsers->push($children->users);
}

// Loop to get the Collection of user
$users = collect();
foreach($childrenUsers as $nCollect){
    foreach($nCollect as $user){
        $users->push($user);
    }
}

return response()->json($users);

My goal is to get the users under a particular parent_id... I don't know how to query it so I used the collection but I think it's not a very good idea.  TY

A:

You can use the whereHas to get the expected result. 
$users = User::whereHas('roles', function() {
    //Get the roles where the parent_id is the (minimum) parent_id from the user roles
    return $query->where('parent_id', Auth::user()->roles()->orderBy('parent_id', 'ASC')->first()->parent_id);
});

More info at https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence

