I have a Laravel project with Categories and Children - I've got this function in my model:
public static function tree() {
return Category::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', NULL)->get();
}
Which I then call with
$categories = Category::tree();
And on the view I have:
@foreach($categories as $index => $category)
{{ $category->title }}
@foreach($category['children'] as $child)
{{ $child->title }}
@endforeach
@endforeach
That works fine - but I'm trying to sort the children alphabetically now.
I've tried this:
public static function tree() {
return Category::with([implode('.', array_fill(0, 100, 'children')) => function($query) {
$query->orderBy('title', 'ASC');
}])->where('parent_id', '=', NULL)->get();
}
I've also tried return Category::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', NULL)->orderBy('title)->get();
but that just orders to parent categories.
But it doesn't sort them. Anyone got any ideas?
Thanks.
--EDIT--
Following Tim's suggestion on a better way, I now have:
public function children() {
return $this->hasMany('App\Category', 'parent_id', 'id');
}
public function childrenCategories()
{
return $this->children()->with('childrenCategories');
}
Then...
$categories = Category::with(['childrenCategories' =>
function($query) {
$query->orderBy('title', 'ASC');
}])->where('parent_id', '=', NULL)->get();
Which works, but not the ordering part. Any suggestions?