1

I need your help with multilevel menu created in laravel, also with an opinion to sort. I have database structure like this: enter image description here

structure_id is primary key. structure_name is a name, which will be display on front-end. structure_url is url, which the anchor will point to. module_id is irrelevant here (need for my uses inside app). sort_position is important. It's integer from 1 to x. I will order the menu items asc/desc by this number. I also need to have an opinion to change order (I think I could be able to code it myself... I hope). I have really no idea, what to do with sort_position while in submenus... parent_id is an attribute, which says, menu item has a parent in the other menu item. So if this value is 0 (like default), the item is up. If the item's parent_id is f.e.: 2, it means, the item belongs under structure_id = 2

I have tried some futile experiments, but I have no chance to do it myself. I am really beginner in laravel, so I hope anyone could help me

1
  • What's the problem? You can specify the order (sort_position) manually, when adding / editing a menu item. Jan 29, 2018 at 22:53

1 Answer 1

0

Here are the step by step I'm using to get multilevel menus :

Table "menus"

id, title, order, parent_id

Model

class Menu extends Model
{
    public function children()
    {
        return $this->hasMany(self::class , 'parent_id', 'id')->orderBy('order');
    }
}

Controller

class MenuController extends Controller
{
    public function index()
    {
        $menus = Menu::where('parent_id', 0)->orderBy('order', 'ASC')->get();
        return view('menu', compact('menus'));
    }
}

View

@foreach($menus as $menu)
    @foreach($menu->children => $child)
        <h4>{{ $child->title }}</h4>
    @endforeach
@endforeach
7
  • Doesn't work bro. Could you please add full step-by-step tutorial, how to do it? I'm really new to laravel :(
    – user4370900
    Jan 30, 2018 at 19:32
  • I did something by this example: stackoverflow.com/questions/21305111/… however I get always empty array as a result. What's wrong? :(
    – user4370900
    Jan 30, 2018 at 20:36
  • @MegoSoft, please see my update step by step to get multilevel meus.
    – Saly
    Jan 31, 2018 at 1:56
  • Thank you a lot. It was helpfull. I have just one question. $menus = Menu::where('parent_id', 0)->orderBy('order', 'ASC')->get(); Is it possible to add ->join() here? I need to connect to another table to get modul name.
    – user4370900
    Jan 31, 2018 at 18:55
  • Yes, you can. But you must specific Menu ID in select.
    – Saly
    Feb 1, 2018 at 1:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.