DEV Community

Ali Shikhiyev
Ali Shikhiyev

Posted on

I'm trying to display all products from a category and it's all sub-categories

Here's my categories table structure :

id parent_id name
1 NULL Vehicles
2 1 Cars
3 2 Motorcycles

but i only get parent and its sub data. i want to get parent sub and subsub data.

here is my category model

public function subproducts()
{
return $this->hasManyThrough(Product::class, self::class, 'parent_id', 'category_id');
}

public function products() {
return $this->hasMany(Product::class);
}

}

here is my product

public function categories() { return $this->belongsTo(Category::class, 'category_id'); }

and this is the controller

$category = Category::with(['products', 'subproducts'])->where('slug', $slug)->first();
$allProducts = $category->products->merge($category->subproducts);

dd($allProducts);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)