在laravel中从数据库创建,排序菜单和子菜单

I'm trying to build menu section which is being fetched from the database, I've menus and sub menus too. I've mentioned a column with the name parent_id if NULL represents it is a parent element if any id is present it is submenu of that particular id of menu element. following is my table

/***************** Menu Elements Table ****************/
|id |   name     |   link    | parent_id | sort_id |
____________________________________________________
|1  | Home       | home      |    NULL   |   NULL  |
|2  | About Us   | about-us  |    NULL   |   NULL  |
|3  | Services   | services  |     2     |     2   |
|4  | Vision     | vision    |     2     |     1   |
|5  | Contact us | contact-us|    NULL   |   NULL  |

and menu to be in format something like this:

<ul id="main-nav">
    <li class="menu-item"><a href="index">Home</a></li>
    <li class="menu-item"><a href="about-us">About Us</a>
        <ul class="sub-nav">
            <li><a href="vision">Vision</a></li>
            <li><a href="services">Services</a></li>
    </li>
    <li class="menu-item"><a href="contact-us">Contact us</a></li>
</ul>

Menu is also sorted according to the sort_id

Till now I'm able to sort the menu elements but I want the sort to be parent_id specific.

$menu_elements = MenuElements::orderBy('sort_id', 'asc')->get()->all();

I'm bit confused how to achieve this. Help me out.

Thanks

You can just add another orderBy():

$menu_elements = MenuElements::orderBy('parent_id', 'asc')->orderBy('sort_id', 'asc')->get()->all();

UPDATE

To do this in the view I would just change your query to:

$menu_elements = MenuElements::all();

Then in your view:

<ul id="main-nav">
    @foreach($menu_elements->where('parent_id', null) as $parent_item)
        <li class="menu-item">
            <a href="{{ $parent_item->link }}">{{ $parent_item->name }}</a>
            @php
                $children = $menu_elements->where('parent_id', $parent_item->id);
            @endphp
            @if(!$children->isEmpty())
                <ul class="sub-nav">
                    @foreach($children->sortBy('sort_id') as $child)
                        <li><a href="{{ $child->link }}">{{ $child->name }}</a></li>
                    @endforeach
                </ul>
            @endif
        </li>
    @endforeach
</ul>