Product filter by attribute values

In admin section I can add product and in product/edit page I can add attribute values to product for exemple I can add color:red with price and quantity for the product and it works but in products page in filter section if I click for exemple red and click filter it return “no products found” but I have a product with this attribte value so how to solve this and thank you very much

to filter products in products page:

productssidebar.blade.php:

@foreach ($attributes  as $attribute)
	<h3>{{ $attribute->name }}</h3>
	<ul>
		@foreach($attributeValues as $attributeValue)
		 @if ($attributeValue->attribute_id == $attribute->id)

		<li><a href="{{ url('products?value='. $attributeValue->value) }}"> {{ $attributeValue->value  }}</a></li>
						
		@endif
	@endforeach

 </ul>
@endforeach

productController:

  public function index( Request $request)
    {   
    
  $this->data['attributes']=Attribute::all();
  $this->data['attributeValues']=AttributeValue::all();
  
        $this->data['products'] = $this->productRepository->paginate(9, $request);
        
   
        return view('site.pages.products', $this->data);
       
}

productRepository:

 public function paginate($perPage, $request)
    {
        $products = Product::active();

        $products = $this->filterProductsByAttribute($products, $request);
       

        return $products->paginate(30);
    }

private function filterProductsByAttribute($products, $request)
    {
        if ($attributeValueValue = $request->query('value')) {
            $attributeValue = AttributeValue::where('value', $attributeValueValue)->firstOrFail();
            
            $products = $products->whereHas(
                'attributes',
                function ($query) use ($attributeValue) {
                    $query->where('attribute_id', $attributeValue->attribute_id)
                        ->where('value', $attributeValue->value);
                }
            );
        }

        return $products;
    }

product.php:

 
  public function attributes()
    {
        return $this->hasMany(ProductAttribute::class);
    }

productAttribute.php:

protected $fillable = ['attribute_id', 'product_id', 'value', 'quantity', 'price'];
 public function product()
    {
        return $this->belongsTo(Product::class);
    }

Attribute.php:

  protected $fillable = [
        'code', 'name', 'frontend_type', 'is_filterable', 'is_required'
    ];

 public function values()
    {
        return $this->hasMany(AttributeValue::class);
    }

AttributeValue.php:

  protected $fillable = [
        'attribute_id', 'value', 'price'
    ];


  public function attribute()
    {
        return $this->belongsTo(Attribute::class);
    }

   
    public function productAttributes()
    {
        return $this->belongsToMany(ProductAttribute::class);
    }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.