Category Tree in Laravel 4

I am trying to create a website that will allow you to place items in specific categories. Categories will almost always have at least one category of parents, and I would like to be able to display a “tree” of these categories so that users can navigate categories and articles. Bit category will contain columns id, parent_id, cat_name.

Is there a more efficient way to do this in laravel, rather than looking for top-level categories and then looping around to find all the subcategories in each? Where is the best way to execute logic and what is the best way to pass this information into a view?

If I need more clarification, let me know. As I said, I'm pretty new to laravel and frameworks in general, so I might be missing something obvious.

+4
source share
2 answers

You can define relationships in Laravel to automatically load object relationships.

See Relations document and Lively Download

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 can even do (although I'm not sure) Category::with('subcategories.subcategories');

+3
source

Handling a nested set manually is quite difficult. I suggest you use an existing package:

Baum

Baum is an implementation of the Nested Set template for the Laravel 4 Eloquent ORM.

+1

Source: https://habr.com/ru/post/1547597/


All Articles