Ali Shaukat
Ali Shaukat

Reputation: 965

Laravel orderBy on with

I have problem with eloquent query. I am using one to Many Relationship to get 'MenuItems' With the 'Menu'. I want to get all menuItems of a particular menu in sorted by 'sort_order' field Using the code below:

Menu::where('slug', 'main-navigation')->with('MenuItems')->orderBy('MenuItems.sort_order', 'asc')->get();

It is not working, is it possible to do it with eloquent? If yes then how?

Upvotes: 0

Views: 307

Answers (1)

Ashwini G.
Ashwini G.

Reputation: 264

try this

 Menu::where('slug', 'main-navigation')->with([
     'MenuItems' => function($query) {
          $query->orderBy('MenuItems.sort_order', 'asc')
     }
])->get();

This will sort all the menu-items under each menu as per sort_order.

Upvotes: 3

Related Questions