This repository accompanies the article Managing Hierarchical Data in Laravel. It provides practical implementations and benchmarks for three prominent techniques used to store and query hierarchical (tree-structured) data within the Laravel framework.
- Recursive Eloquent Relationships (native Laravel approach)
- Adjacency List (powered by
staudenmeir/laravel-adjacency-list) - Nested Set Model (using
kalnoy/nestedset)
Each implementation uses a sample dataset consisting of 1,000 auto part categories to illustrate real-world scalability and performance.
- Docker
- PHP 8.3+, Composer, Laravel 13
git clone https://github.com/tegos/laravel-hierarchical-data.git
cd laravel-hierarchical-data
cp .env.example .env
docker compose up -d --build
docker compose exec app composer install
docker compose exec app php artisan key:generate
docker compose exec app php artisan migrate --seedAll endpoints output the complete category tree in JSON format.
| Structure | HTTP Method | Endpoint |
|---|---|---|
| Recursive Eloquent | GET |
/api/v1/catalog/categories/tree-recursive |
| Adjacency List | GET |
/api/v1/catalog/categories/tree-adjacency |
| Nested Set | GET |
/api/v1/catalog/categories/tree-nested-set |
To compare the performance of each retrieval strategy, execute:
docker compose exec app php artisan catalog:category-benchmark-treeThe command returns execution times for all supported methods.
Additional maintenance commands:
# Rebuild nested set lft/rgt values
docker compose exec app php artisan catalog:category-repair-tree
# Print random category paths (adjacency list ancestors)
docker compose exec app php artisan catalog:category-random-pathA single command runs the whole pipeline (same entrypoint as CI):
docker compose exec app composer testIt executes, in order:
| Script | Tool |
|---|---|
test:unit |
PHPUnit feature tests |
test:types |
PHPStan (larastan, level 5) |
test:lint |
Pint style check |
test:rector |
Rector dry-run (PHP 8.3 + Laravel sets) |
test:class-leak |
Unused class detection |
Auto-fixers: composer lint (Pint) and composer rector.
app– Laravel PHP 8.4 app containernginx– Web server (accessible vialocalhost:8000)mysql– MySQL 8.0 database
For the complete configuration, refer to docker-compose.yml.
Further technical explanation and usage details are available in the article:
👉 Managing Hierarchical Data in Laravel
Contents include:
- Technical breakdowns and code samples for each tree structure in Laravel
- Comparative analysis of recursive, adjacency list, and nested set models
- Benchmark data using over 1,000 product categories
- Guidance for selecting the optimal strategy for your API or catalog implementation
