I have stored Products and their attributes, and attribute options as well in the database.
In this way, I sent product attribute_data into Database
Function
$data['product_attributes'] = Pro_attributes::with('attribute_options')->get();
Blade File (Displaying Data)
@foreach ($product_attributes->unique('name') as $item)
<div class="sidebar__item sidebar__item__color--option">
<h4>{{ $item->name }}</h4>
@php
$options = $product_attributes
->where('name', $item->name)
->flatMap->attribute_options->unique('name')
->sortBy('name');
@endphp
@foreach ($options as $option)
<div class="form-check">
<input class="form-check-input" type="radio" value="{{ $option->id }}"
id="{{ $option->id }}"
name="{{ strtolower(str_replace(' ', '-', $item->name)) }}">
<label class="form-check-label"
for="{{ $option->id }}">{{ $option->name }}</label>
</div>
@endforeach
</div>
@endforeach
Result
Frontend Displaying Attributes and options
Now After Submitting form dd($request->all());
array:4 [▼ // appHttpControllersFrontendShopController.php:59
"color" => "47"
"size" => "50"
]
as my relations are
from product.php
public function attributes()
{
return $this->hasMany(Pro_attributes::class, 'product_id');
}
from pro_attibutes.php
public function attribute_options()
{
return $this->hasMany(pro_attributes_options::class, 'attribute_id');
}
and from pro_attibutes_options.php
public function attribute()
{
return $this->belongsTo(Pro_attributes::class, 'attribute_id');
}
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Now Please help to Filter products dynamically having these attributes
as I have tried much to make this functionality but i can’t.
i do not want to filter this way
if ($request->filled('color')) {
$color = (array) $request->input('color');
$products->whereHas('attributes.attribute_options', function ($query) use ($color) {
$query->whereIn('id', $color);
});
}
because in this way we’ve to create code one by one for each attribute
but I want to make it dynamic because in the future I have to create more filters.
Please help me I am waiting for your response.