Returning all the grandson in Laravel

49 views Asked by At

in my models, I have those relations:

  • Category -> Subcategories : hasMany
  • Subcategories -> Category : belongsTo
  • Subcategory -> Products : hasMany
  • Products -> Subcategory : belongsTo
  • Category -> Products : hasManyThrough

I want to display all the products of a category through the subcategory table.

So, I wrote this code, but I have a problem at the dd($products), because only one products is got.

Could you please help me to fix the issue in my code ?

        public function show(Category $category)
        {
             $subcategories = Subcategory::join('categories','subcategories.category_id','categories.id')
            ->where('subcategories.category_id',$category->id)
            ->select('subcategories.id')
            ->get();

// dd($subcategories); give 3 different subcategories to me -> OK

            foreach ($subcategories as $subcategory) {
                $query = Product::where('products.subcategory_id',$subcategory->id)->get();
            }
            $products = $query;

// dd($products); give only 1 product to me (in fact, there are 4 products) -> NOK

            $data = [
                'title'=> $description = $category->title,
                'description'=> $description,
                'heading'=> config('app.name'),
                'category'=>$category,
                'subcategory'=>$subcategories,
                'products'=>$products,
            ];
            // dd($data);
            return view('category.show', $data)->with('products', $products);
1

There are 1 answers

8
Alejandra Jorge On

It seems you are just redeclaring the $query variable instead of treating it as an array, that's why is just bringing one:

 foreach ($subcategories as $subcategory) {
                $query[] = Product::where('products.subcategory_id',$subcategory->id)->get();
            }
            $products = $query;