Skip to content

Instantly share code, notes, and snippets.

@etrepat
Last active April 8, 2021 15:57
Show Gist options
  • Save etrepat/6920301 to your computer and use it in GitHub Desktop.
Save etrepat/6920301 to your computer and use it in GitHub Desktop.
Traversing the Hierarchy Tree with Baum - An Example

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