Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Tree Helper Laravel Package

pbergman/tree-helper

Laravel package for working with hierarchical tree data in Eloquent models. A trait and query helpers let you fetch parents, children, ancestors, descendants, and siblings, and build nested trees from flat records for categories, menus, and threaded content.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal steps:

  1. Install: composer require pbergman/tree-helper (the package name and repository name differ — tree-helper on Packagist maps to the pbergman/tree-printer repo).
  2. Read the source first. This is a tiny package (one or two classes in src/), so the fastest way to learn the exact API is to open the main class rather than rely on stale README examples.
  3. First use case: turn a nested PHP array into a readable ASCII tree for debugging configuration, permissions, or nested payloads.
use Pbergman\TreePrinter\TreePrinter; // verify namespace/method names against src/

$data = [
    'app' => [
        'config' => ['database.php', 'queue.php'],
        'routes' => ['web.php', 'api.php'],
    ],
    'public' => ['index.php', 'assets'],
];

echo (new TreePrinter())->render($data);

If the class exposes static helpers (common for "dump"-style utilities), the call may look like TreePrinter::print($data) — check the source for the actual entry point before wiring it into your code.

Implementation Patterns

Debugging nested arrays and config. The primary value is turning a deep array into something a human can scan in a log or terminal. Wrap it in a tiny dev-only helper so you can drop dumpTree($array) anywhere without leaking it into production output paths.

if (app()->environment('local')) {
    logger()->debug((new TreePrinter())->render($payload));
}

Adjacency lists from the database. Most Laravel tree data is stored flat (id, parent_id) — this package renders a nested array, so normalize first. A small recursive builder is usually enough:

function buildTree(Collection $rows, $parentId = null): array
{
    $branch = [];
    foreach ($rows->where('parent_id', $parentId) as $row) {
        $children = buildTree($rows, $row->id);
        $branch[$row->name] = $children ?: null;
    }
    return $branch;
}

echo (new TreePrinter())->render(buildTree(Category::all()));

Custom node formatting. Where the package accepts a callback/closures formatter, use it to attach counts, IDs, or status markers to labels. Keep the formatter pure (return a string) — side effects make the output order-dependent and hard to test.

Artisan command for inspection. A dev-only command is the natural home: php artisan app:tree or php artisan config:tree that prints the tree of a config subtree or a file-system directory. Cache the compiled output so it doesn't rebuild on every keystroke if you add a watch mode.

Directory trees. If you're using it for files, combine with RecursiveDirectoryIterator → nested array, then render. This is the "poor-man's tree command" use case and is a common reason to reach for this package.

Symfony Console / CI logs. The output is just a string, so pipe it through $this->line() or OutputInterface::write(). Consider wrapping in a SymfonyStyle block for a titled section.

Gotchas and Tips

  • UTF-8 branch characters. ├──, └──, and │ render as garbage in some Windows consoles, older CI log viewers, and locales without UTF-8. If output is captured into logs you inspect on multiple platforms, be prepared to post-process to ASCII (+--, `--) or configure an ASCII mode if the package offers one.
  • Multi-line node labels break alignment. If your formatter returns strings containing \n, the tree indentation will look wrong on continuation lines. Pre-collapse newlines to a space or ↳ before returning.
  • Cyclic or self-referencing structures hang. Deep or accidentally circular references (an object pointing back to its parent) will recurse until memory exhaustion. Guard your array builder with a visited-set; the renderer can't protect you from input you already built.
  • Numeric keys are ambiguous. Arrays keyed by IDs render the IDs as labels — that's usually fine, but mixed key types produce inconsistent alignment. Normalize labels to strings in your formatter.
  • No built-in sorting. Sibling order is your input order. Sort the nested array (or the flat collection) before rendering if you want deterministic output for snapshots/tests.
  • Old package, newer PHP. Last release is early 2022, so verify it runs on PHP 8.2/8.3 in CI before depending on it in a dev dependency you share with a team. If it's only used in local debug helpers, pin it under require-dev.
  • Zero dependents is a signal. Not many others are exercising edge cases, so treat it as a small utility you own rather than a well-trodden library — keep the call sites behind your own tiny wrapper so you can swap the renderer later without touching every command.
  • Extension point. If labels need per-node styling (colors, icons), prefer injecting a formatter closure over subclassing the printer — the class is small enough that forking/subclassing becomes a maintenance burden on upgrade.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource