title: Threaded Comments in Laravel w/Eloquent
body: <p>I have user profiles that allow users to leave messages for each other. (Think Facebook/MySpace)...</p>
  
  <p>Given a <code>profile_messages</code> table with the following fields <code>id</code>, <code>user_id</code>, <code>author_id</code>, <code>parent_id</code>, and <code>message</code>, how would I efficiently display them in a threaded layout?  </p>
  
  <p><em>Note: The comments will only be 1 level deep.</em></p>
  
  <p>Currently, I'm fetching all of the relevant comments, then rebuilding the collection to have a <code>$messages</code> with a sub-collection of <code>replies</code> on each item. </p>
  
  <pre><code>$messages = new Collection();
  $replySets = [];
  
  foreach ($user-&gt;profileMessages as $message)
  {
      $parentId = $message-&gt;parent_id;
  
      if ($parentId == 0)
      {
          $messages-&gt;put($message-&gt;id, $message);
      }
      else
      {
          $replySets[$parentId][] = $message;
      }
  }
  
  foreach ($replySets as $parentId =&gt; $replies)
  {
      $parent = $messages-&gt;get($parentId);
  
      if (isset($parent))
      {
          if ( ! isset($parent-&gt;replies))
          {
              $parent-&gt;replies = new Collection();
          }
  
          foreach ($replies as $reply)
          {
              $parent-&gt;replies-&gt;push($reply);
          }
      }
  }
  
  // Pass $messages to the view
  </code></pre>
  
  <p><br>
  This works great. However, I can't help but to think there is a better way of doing this... Is there a better way to do this, or perhaps a way to make use of the relationships to get a result set matching the <code>$profileMessage-&gt;replies</code> structure?</p>