How to fetch data of three level categories (Category,SubCategory,SubCategoryThree) and display relative data under selected category

Viewed 168

I have three tables. The structure is:

1. categories

    id - integer

    name - string

2. sub_Categories

    id - integer

    category_id - integer

    name - string


3. sub_catergory_threes

    id - integer

    sub_Category_id - integer

    name- string

Now I want to show three level categories like, Category and when hover on any category item, Sub Categories of that category shows and when hover on any SubCategory item, Sub_Categories_Three of that SubCategory shows

im using laravel eloquent here are My Models

Category Model

public function subcategories(){
    return $this->hasMany('App\SubCategory');
}

SubCategory Model

public function subcategoriesthree(){
    return $this->hasMany('App\SubCategoryThree');
}

public function category(){
    return $this->belongsTo('App\Category');
}

SubCategoriesThree Model

public function subcategory(){
    return $this->belongsTo('App\SubCategory');
}
2 Answers

You can use ELoquent relationship to load all the related data

$categories = App\Category::with('subcategories.subcategoriesthree')->get();

This will load all the categories along with its subcategories and subsubcategories

If you need to load it dynamically, then in your controller you can use

public function loadSubCategory($categoryId)
{
    $category = App\Category::findOrFail($categoryId);
    $subcategories = $category->subcategories()->get();
    return $subcategories;
}

public function loadSubSubCategory($subcategoryId)
{
    $subcategory = App\SubCategory::findOrFail($subcategoryId);
    $subsubcategories = $subcategory->subcategoriesthree()->get();
    return $subsubcategories;
}

So you can edit your model like this:

SubCategory

public function subcategoriesthree(){
    return $this->hasMany('App\SubCategoryThree');
}

public function category(){
    return $this->belongsTo('App\Category', 'category_id');
}

SubCategoriesThree

public function subcategory(){
    return $this->belongsTo('App\SubCategory', 'sub_Category_id');
}

And in your controller:

$categories = Category::with(['subcategories', 'subcategories.subcategoriesthree'])->get();

And after that you can dd($categories) and see under subcategories are subcategoriesthree.

Related