Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DPST's avatar
Level 1

[5.2] Output NestedSet with Blade

I am using https://github.com/lazychaser/laravel-nestedset to have infinite deeply nested categories and took the code from http://www.sitepoint.com/laravel-blade-recursive-partials/ to output it into my blade.

nav.blade.php

@each('partials.category', Category::tree(), 'category', 'partials.categories-none')

category.blade.php

<li>{{ $category['name'] }}</li>

@if (count($category['children']) > 0)
    <ul>
    @foreach($category['children'] as $category)
        @include('partials.category', $category)
    @endforeach
    </ul>
@endif

The problem is that the output isn't the same as the one in the sitepoint article.

My output looks like this.

Root
     - Child 1
     - Child 2
     - Child 3
- Child 1 of Root
- Child 2 of Root
- Child 3 of Root

So the children of root get output twice, once under the root how they are supposed to and once on their own after the root like they are root nodes too. I guess it is an issue with the blade code, so how would I output a nested set correctly with root and child nodes in blade?

0 likes
5 replies
frezno's avatar

@DPST - why don't you do it the way as lazychaser shows in his documentation?

DPST's avatar
Level 1

Not really seeing how I would put the traverse example into pretty blade code since I need to output it as an ul list.

Edit: I quickly made this work, but no idea how I would translate that into Blade code.

@php
    $nodes = Category::get()->toTree();

    $traverse = function ($categories, $prefix = '<li>', $suffix = '</li>') use (&$traverse) {
        foreach ($categories as $category) {
            echo $prefix.$category->name.$suffix;

            $hasChildren = (count($category->children) > 0);

            if($hasChildren) {
                echo('<ul>');
            }

            $traverse($category->children);

            if($hasChildren) {
                echo('</ul>');
            }
        }
    };

    $traverse($nodes);
@endphp
1 like

Please or to participate in this conversation.