Skip to content

Instantly share code, notes, and snippets.

@wulongqiu
Forked from etrepat/traversing-example.md
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wulongqiu/27311e54e367423c8a71 to your computer and use it in GitHub Desktop.
Save wulongqiu/27311e54e367423c8a71 to your computer and use it in GitHub Desktop.

The simplest way to traverse the hierarchy tree with Baum is by iterating through the children relation.

<?php

$root = Category::roots()->with('children')->first();

echo "<h3>{$root->name}</h3>";

foreach($root->children as $category) {
  echo "<li>";
  echo "<b>{$category->name}</b>";
  
  if ( $category->children()->count() > 0 ) {
    echo "<ul>";
    foreach($category->children as $subCategory)
      echo "<li>{$subCategory}</li>";
    echo "</ul>";
  }
  
  echo "</li>";
}

This approach is ok if you don't need to go too deep under your hierarchy tree (usually 1 to 3 levels). If you'd need to traverse your tree deeper or, maybe get the full hierarchy tree, you could consider a simple recursive approach.

<?php

$roots = Category::roots()->get();

echo "<ul>";
foreach($roots as $root) renderNode($root);
echo "</ul>";

// *Very simple* recursive rendering function
function renderNode($node) {
  echo "<li>";
  echo "<b>{$node->name}</b>";

  if ( $node->children()->count() > 0 ) {
    echo "<ul>";
    foreach($node->children as $child) renderNode($child);
    echo "</ul>";
  }

  echo "</li>";

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment