Reputation: 279
I'm trying to develop a website that will allow items to be posted under certain categories. The categories will almost always have at least one parent category though, and I'd like to be able to display a 'tree' of these categories for users to be able to navigate the categories and articles. A category DB would contain the columns id
, parent_id
, cat_name
.
Is there a more efficient way to do this in laravel rather than looking for the top level categories then looping round to find all the sub categories in each? Where is the best place to carry out the logic and what's the best way to pass this information to the view?
If more clarification is needed let me know. Like I say I'm pretty new to laravel and frameworks in general so I'm maybe missing something obvious.
Upvotes: 4
Views: 2948
Reputation: 219938
Handling a Nested Set manually is pretty arduous. I suggest you use an existing package:
Baum is an implementation of the Nested Set pattern for Laravel 4's Eloquent ORM.
Upvotes: 1
Reputation: 20554
You can define relations in Laravel to automatically load the relations of an object.
See the doc about Relations and Eager Loading
class Category extends Eloquent
{
public function subcategories() {
return $this->hasMany('Category','parent_id');
}
}
In your controller:
Category::with('subcategories')->get(); //Get all categories and their subcategories
You might even do (altough I'm not sure) Category::with('subcategories.subcategories');
Upvotes: 3