Nitish Kumar Nitish Kumar - 3 months ago 37
JSON Question

Creating menu from JSON data in laravel blade views

I'm trying to have

multi level menu
through
JSON data
, following is my
JSON
format data:

{"pages": [
{"pagelink": "index.html", "pagename": "Mysite", "submenu": [
{"pagelink": "#", "pagename": "sublevel1", "submenu": "NULL"},
{"pagelink": "#", "pagename": "submenu2", "submenu": [

{"pagelink": "#", "pagename": "sublevel2", "submenu": "NULL"}

]
}
]
},
{"pagelink": "templates.html", "pagename": "Templates", "submenu": "NULL"},
{"pagelink": "aboutus.html", "pagename": "About Us", "submenu": "NULL"},
{"pagelink": "contactus.html", "pagename": "Contact Us", "submenu": "NULL"}
]
}


When I was not having
sub menu
field I used to call the menu by following:

<nav id="nav">
<ul id="main-nav" class="hidden-mobile">
@foreach($contents->pages as $pages)
<li class="menu-item-has-children">
<a href="{{ $pages->pagelink }}">{{ $pages->pagename }}</a>
</li>
@endforeach
</ul>
</nav>


When I added submenu I tried using following code:

<nav id="nav">
<ul id="main-nav" class="hidden-mobile">
@foreach($contents->pages as $pages)
<li class="menu-item-has-children">
<a href="{{ $pages->pagelink }}">{{ $pages->pagename }}</a>
@if(isset($contents->pages->submenu))
<ul class="sub-nav">
@foreach($contents->pages->submenu as $submenu)
<li><a href="{{ $submenu->pagelink }}">{{ $submenu->pagename }}</a> </li>
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>
</nav>


But it is not working out.

Please guide me, shall I need to change
JSON data
format or the is there any way out in
blade
file itself.

Answer

You have to call $pages, not $contents->pages

@if(isset($pages->submenu))
    <ul class="sub-nav">
        @foreach($pages->submenu as $submenu)
            <li><a href="{{ $submenu->pagelink }}">{{ $submenu->pagename }}</a> </li>
        @endforeach
    </ul>
@endif

If you would like to create multidimensional JSON, and you don't know, how many nested arrays you will have, you have to create additional blade for submenu

<ul class="sub-nav">
    @foreach($pages->submenu as $submenu)
        <li><a href="{{ $submenu->pagelink }}">{{ $submenu->pagename }}</a> </li>
        @if (isset($submenu->submenu))
            @include('submenu', ['pages' => $submenu->submenu])
        @endif
    @endforeach
</ul>

And then your menu blade will looks like:

<nav id="nav">
    <ul id="main-nav" class="hidden-mobile">
        @foreach($contents->pages as $pages)
            <li class="menu-item-has-children">
                <a href="{{ $pages->pagelink }}">{{ $pages->pagename }}</a>
                @if(isset($pages->submenu))
                    @include('submenu', ['pages' => $pages->submenu])
                @endif
            </li>
        @endforeach
    </ul>
</nav>

This solution should work, if you will remove "submenu": "NULL". If not, you have to additionally check, if element submenu is an array in all conditionals.