I have this function in laravel 9
private function userDirectSubordinates($user_id, $company_id)
{
return User::select(['users.id', 'users.name as label', 'avatar', 'departments.name as department'])
->join('department_user', 'users.id', '=', 'department_user.user_id')
->join('departments', 'departments.id', '=', 'department_user.department_id')
->where('departments.company_id', $company_id)
->whereIn('users.id', function($query) use($user_id) {
$query->select('user_id')
->from('company_user')
->where('superior_id', $user_id);
})
->get();
}
This function return the direct subordinates for the user with id $user_id from the company selected $company_id. Example:
[
["id" => 880, 'label' => 'User 880', 'avatar' => null, 'department' => 'IT'],
["id" => 41, 'label' => 'User 41', 'avatar' => null, 'department' => 'Finance'],
...
]
How can I make a recursive function to get from each user from directSubordinates ... all subordinates. The final array should look like this:
[
["id" => 880, 'label' => 'User 880', 'avatar' => null, 'department' => 'IT',
'children' => [
["id" => 32, 'label' => 'User 32', 'avatar' => null, 'department' => 'IT', 'children' => []],
["id" => 56, 'label' => 'User 56', 'avatar' => null, 'department' => 'IT',
'children' => [
["id" => 21, 'label' => 'User 21', 'avatar' => null, 'department' => 'Maintenance', 'children' => []],
["id" => 687, 'label' => 'User 687', 'avatar' => null, 'department' => 'Development',
'children' => [
["id" => 334, 'label' => 'User 334', 'avatar' => null, 'department' => 'Development', 'children' => []],
["id" => 335, 'label' => 'User 335', 'avatar' => null, 'department' => 'Development', 'children' => []],
]
]
],
]
],
],
...
];
