shankar bhatt
shankar bhatt

Reputation: 21

How to make side bar dynamic according to menus under sub menu in laravel blade?

Here I want submenus of related menu .But This code Give all submenu of all menus added to the nav bar .

<ul>
@foreach($allMenu as $menu)
<ul class="submenu">
    @if(isset($menu->submenus)) 
        @foreach($menu->submenus as $submenu) 
            @if(isset($submenu->page->slug))
                <li class="{{ $request->segment(1) == $submenu->page->slug ? 'active' : '' }}"><a href="{{url($submenu->page->slug)}}">{{ $submenu->name}}</a></li> 
            @else 
            @endif 
        @endforeach 
    @endif
</ul>
@endforeach

Upvotes: 0

Views: 1765

Answers (2)

wadleo
wadleo

Reputation: 101

Your question does not have all the relevant data for us to help you, but I wish to assume your relationship between the menu and submenu models is well implemented(that is a one to many relationship).

You can verify that by checking your database table for submenu and see if each submenu entry has the correct menu id.

Also, you can further debug in your controller by diedumping the allMenu array dd(allMenu). Then break each menu to see the relationships sub object to see each submenu.

You can comment under for further help

Upvotes: 1

spartyboy
spartyboy

Reputation: 426

try it this way instead. Assuming you have a model for category and in your db of category you had a column called parent which is integer if its Null its a main menu else its a submenu.also i would have a function that checks if i have a submenu for the given menu.

public static function hasSubmenu($id){
 $sub = Category::where('parent','=',$id);
   if($sub->count()>0){
    return true;
   }else{
    return false;
   }
}

firstly, i would get all mainmenu like this

<?php $mainMenus = Category::where('parent','=',null)->get();?>
    @foreach ($mainMenus as $mainMenu)
      <ul>
        <li>{{$mainMenu->name}}
              @if(Category(hasSubmeny($mainMenu->id)))
               <ul id="submenu">
                <?php $subMenus = Category::Where('parent','=',$mainMenu->id)?>
                  @foreach($subMenus as $subMenu)
                    <li>{{$submenu}}</li>
                  @endforeach
               </ul>
              @endif
        </li>
      </ul>
    @endforeach

try this please hope it works and suit your usage

Upvotes: 2

Related Questions