php – filter products in hierarchical categories with products with laravel-ThrowExceptions

Exception or error:

this is in laravel 6.x
I made hierarchical categories in same table depend on parent_id , every category has many subcategories and every category has many products, I made filtering for products when user click in category it is show category with all it’s subcategories with them products all things are correct.
but the problem with sub sub categories products they are not filtering like category products and subcategory products. what is the problem.?
is This powerful way for this job.?

this is relations in category model

    public function subcategory()
    {
     return $this->hasMany(self::class,'parent_id','id');
    }

public function products()
        {
            return $this->hasMany('App\product','category_id','id');
        }

public function parentId()
    { 
        return $this->belongsTo(self::class);
    }

 public function scopeCatItem($query , $id)
        {
            return $query->where('id', $id);
        }

and this code in category_products controller

     $data = Category::CatItem($request->catid)->withTranslations($locale)
         ->with([ // start with
      'products' => function($query) use ($company , $volt) { // first parameter
              $query->when($company , function($query) use ($company){
                  $query->where('company_id', $company);
                  });
              $query->when($volt , function($query) use ($volt){
                  $query->where('volt', $volt);
                  });
            },
      'subcategory'  => function($query) use ($company, $volt) {  // second parameter          
            $query->whereHas('products', function ($query) use ($company , $volt) {
              $query->when($company , function($query) use ($company){
                    $query->where('products.company_id', $company);
                  });
              $query->when($volt , function($query) use ($volt){
                    $query->where('products.volt', $volt);
                  });
            });         
      },
      'subcategory.products' => function($query) use ($company, $volt) { // third parameter
              $query->when($company , function($query) use ($company){
                    $query->where('products.company_id', $company);
                 });
               $query->when($volt , function($query) use ($volt){
                    $query->where('products.volt', $volt);
                 });                      
         },
    ]) // close with
    ->get();

this is code in view products blade file

  @if(count($item->subcategory))
    @include('panels.frontend.sub-filtered_products',['subcategories' => $item->subcategory])
  @endif
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *