In my database, I have a Categories table. Categories can have parent categories, making it a recursive relationship
I also have a products table. Each product falls under a category.
Say, for example, I have a tree that looks like this:
Category
Sub-Category 1
Sub-Sub-Category 1
Product 1
Product 2
Product 3
Product 4
Sub-Sub-Category 2
Product 5
Product 6
Product 7
Product 8
Sub-Category 2
Sub-Sub-Category 3
Product 9
Product 10
Product 11
Product 12
If I do $SubCategory1->products
, I want it to give me Products 1-8
If I do $SubSubCategory3->products
, I want it to give me products 9-12
If I do $Category->products
, I want it to give me all products
Basically, I want the category to give all products that fall under it
Suppose your Model name is Category
Create a function on Category model
Using above method on your controller
please try the below Has Many Through relation and post the result
Then you can use
$category->products;
to find your productsThis way works very good:
After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.