Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bipin's avatar
Level 2

Invalid argument supplied for foreach()

@Snapey Category.php Model

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

public function subCategories()
{
return $this->hasMany(SubCategory::class,'id_category');
 }

SubCategories.php Model public function products() { return $this->hasMany(Product::class,'id_subcategory'); } public function category() { return $this->belongsTo(Category::class); } Product.php Model

 public function category()
 {
return $this->belongsTo(Category::class);
 }

in controller:

    $categories = Category::with('subcategories.products')->get();

in view:

   <ul>
         @foreach($categories as $category)
                echo'<li value=""> {{$category->namecategory}}';
              
                  <ul>
                  @foreach($category->subCategories as $subCategory)
                     echo'<li value="">{{$subCategory->namesubcategory}}';

                                <ul>
                         @foreach($subCategory->products as $product)
                              echo'<li value="">{{$product->namesubling}}</li>';
                                 @endforeach
                               </ul>
                              </li>
                  @endforeach
                        </ul>

                     </li>
          @endforeach
             </ul>

its throwing error Invalid argument supplied for foreach() if i remove 2 foreach then its working i know that its not taking data as array so its throwing error but how i can do so i can achieve my desire view

       mobile and accessory
                mobile
                     iphone
                mobile cover
                    iphone cover 

i m try to achieve like this don't know how i do that please help me guys

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

if your relationship is subcategories then you need to use the same name in the foreach

@foreach($category->subCategories as $subCategory) here you have capital C

also, you don't need to use echo in your blade files.

build it up slowly. start with the outer loop, listing all categories, then add the subcategories and then add products

if you get lost, use {{ dump(variable) }} so that you can see the the structure. look in the relations element for the names of the children

1 like
bipin's avatar
Level 2

thanks @Snapey i don't know how to thank you........... thankss alot its clear my concept about relationship

Please or to participate in this conversation.