lukascivil/treewalker
Laravel package for walking, searching, and manipulating tree structures with a simple API. Traverse nodes, run callbacks, and query descendants/ancestors efficiently—useful for nested categories, menus, and other hierarchical data.
Start by installing the package via Composer:
composer require lukascivil/treewalker
Then, import the core classes into your workflow. The main entry point is the TreeWalker class—create an instance with your tree data and configure how children are accessed (e.g., using ->childrenAccessor('subitems') if your data uses a custom key like subitems instead of children).
Your first use case is likely transforming a nested menu array into a flat list of breadcrumb strings:
use Lukascivil\TreeWalker\TreeWalker;
$walker = new TreeWalker($menuTree);
$breadcrumbs = $walker->walk(function ($node) {
return $node['title'];
})->toArray();
Check the examples/ directory (if present in the repo) or read the PHPDoc for TreeWalker::walk(), map(), filter(), and reduce().
walk() with a callback to collect paths or map() to inject computed fields (e.g., depth, isActive) while preserving tree shape.filter() to exclude inactive sections and map() to normalize keys.walk() with node-type checks:
$walker->walk(function ($node) {
if ($node['type'] === 'array') {
$node['items'] ??= [];
}
return $node;
});
reduce() to compute summary stats (e.g., total leaf count, max depth, cumulative price) in a single pass.filter(), map(), and walk() for declarative pipelines—each operation returns a new TreeWalker for chaining.__get), define a robust childrenAccessor callback instead of relying on defaults.walk() processes the root node—wrap your callback in if ($depth > 0) if you want to skip it.walk() callback should return transformed node data (array/object); non-serializable returns may cause unexpected behavior in downstream operations like toArray().map() mutates references unless you explicitly clone nodes (return (array) $node; or clone $node). Use clone to avoid side effects.TreeWalker::flatten($tree)—use these for quick conversions without instantiation.How can I help you explore Laravel packages today?