Skip to content
Advertisement

Sorting Children in Laravel : How do I sort children by name?

Below is my controller code

$categories = Category::where('parentId', '=', 0)
                                ->with('children')
                                ->orderBy('name', 'asc')
                                ->get();    
return view('home', compact('categories'));

When I access my categories and its children in the view, the categories seem to be sorted by name but the children categories are not. How do I sort the children categories as well by name?

Also, is it possible to sort the categories using a different criteria than the children eg. By position for categories and name for children. If yes, how?

Advertisement

Answer

You need to apply order by on children, not categories. The following code will do the trick:

$categories = Category::whereParentId(0)
  ->with(['children' => function($query) {
    $query->orderBy('name', 'asc');
  }])
  ->get();    
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement