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!