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>";
}