title: How to get the Hierarchy recursively in laravel
body: <p>I have 2 tables i.e. <code>users</code> and <code>user_managers</code>, with the following structure and data:</p>
  <p><strong>users</strong></p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>id</th>
  <th>name</th>
  <th>employee_number</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>Employee One</td>
  <td>ACB1234</td>
  </tr>
  <tr>
  <td>2</td>
  <td>Employee Two</td>
  <td>XYZ1234</td>
  </tr>
  <tr>
  <td>3</td>
  <td>Employee Three</td>
  <td>EFG1234</td>
  </tr>
  <tr>
  <td>4</td>
  <td>Employee Four</td>
  <td>HIJ1234</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p><strong>user_managers</strong></p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>id</th>
  <th>user_id</th>
  <th>manager_of_user_id</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>1</td>
  <td>2</td>
  </tr>
  <tr>
  <td>2</td>
  <td>2</td>
  <td>3</td>
  </tr>
  <tr>
  <td>3</td>
  <td>4</td>
  <td>1</td>
  </tr>
  <tr>
  <td>4</td>
  <td>5</td>
  <td>4</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I want a recursive function to get the complete chain of the managers. For example, if query for <code>user_id = 4</code>, I should get the following result:</p>
  <p><strong>result</strong></p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>user_id</th>
  <th>name</th>
  <th>employee_id</th>
  <th>comments</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>Employee One</td>
  <td>ABC1234</td>
  <td>user managed by 4</td>
  </tr>
  <tr>
  <td>2</td>
  <td>Employee Two</td>
  <td>XYZ1234</td>
  <td>user managed by 1</td>
  </tr>
  <tr>
  <td>3</td>
  <td>Employee Three</td>
  <td>EFG1234</td>
  <td>managd by user 2</td>
  </tr>
  <tr>
  <td>5</td>
  <td>Employee Five</td>
  <td>JKL1234</td>
  <td>manager of user 4</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>The table above is just for the clarification, I am looking for a recursive function to get the above result.
  I have tried the below solution but it is working for only 1 level.</p>
  <pre><code>public static function getCompleteChain(User $user)
      {
          $managerUsers = $user-&gt;managers;
  
          foreach ($managerUsers as $manager) {
              $manager-&gt;user = User::where('employee_id', $manager-&gt;manager_of_user_id)-&gt;first();
              self::getCompleteChain($manager-&gt;user);
          }
          return $managerUsers;
      }
  </code></pre>
  <p>Thanks in advance.</p>