Reputation: 117
Model:
class Menu extends Model { protected $table = 'menus'; public function sub_menu(){ return $this->hasMany('App\Menu', 'parent_id'); } }
Controller:
class MenuController extends Controller { public function index() { $menus = Menu::where('parent_id', 0)->get(); return view('admin.menus.index',compact('menus')); } }
View:
<ul>
@foreach($menus as $menu)
<li>{{ $menu->title }}
@if($menu->sub_menu->count() > 0)
<ul>
@foreach($menu->sub_menu as $sub)
<li{{ $sub->title }}</li>
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>
Table Structure:
---------------------------------------------------------------------- id | title | parent_id ---------------------------------------------------------------------- 1 | Home | 0 ---------------------------------------------------------------------- 2 | Product1 | 0 ---------------------------------------------------------------------- 3 | Product1.1 | 2 ---------------------------------------------------------------------- 4 | Product1.1.1 | 3 ---------------------------------------------------------------------- 5 | Product1.1.2 | 3 ----------------------------------------------------------------------
It's show only 2 levels but I need multiple levels, please help!
Upvotes: 1
Views: 2794
Reputation: 17658
You can try it using recursion as:
<ul>
@foreach($menus as $menu)
<li>
{{ $menu->title }}
@if($menu->sub_menu->count())
{!! view('admin.menus.index', ['menus' => $menu->sub_menu]) !!}
@endif
</li>
@endforeach
</ul>
It will work when your view has only the above content otherwise, you have create new partial and call it recursively.
Just be careful you may end in an infinite loop using recursion.
Upvotes: 2