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

- 1 answer

Ad

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?

Ad

Answer

Ad

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();    
Ad
source: stackoverflow.com
Ad