Answer the question
In order to leave comments, you need to log in
How to optimize the display of parent and child categories in the form of a "tree"?
Good day!
Dear Khabrovites, I just started to learn Laravel and faced the problem of OPTIMIZING the output of parent and child categories in the form of a "tree".
It is required to display about forty parent and almost a hundred child categories.
There are two tables categories and subcategories, the last one has a category_id foreign key associated with the id in the categories table. There are also two models: Category and Subcategory with a one-to-many relationship.
In the controller I write:
class CategoryController extends Controller
{
public function index()
{
$categories = Category::with('subcategory')->get();
return view('dashboard.categories.index', compact('categories'));
}
}
@foreach($categories as $category)
{{ $category->title }}
@foreach($category->subCategory as $sub_category)
{{ $sub_category->title }}
@endforeach
@endforeach
select * from `subcategories` where `subcategories`.`category_id` = 1 and `subcategories`.`category_id` is not null
Answer the question
In order to leave comments, you need to log in
You are messing around somewhere and doing something different than what you write here. Try replacing subcategory with subCategory in the main query
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question