Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
Altaf D Avatar asked Dec 06 '25 00:12

Altaf D


1 Answers

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();    
like image 99
jedrzej.kurylo Avatar answered Dec 07 '25 13:12

jedrzej.kurylo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!