Ad
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?
Ad
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();
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad