This is Ahmad Raza.
I’m working on E-commerce Project. I am trying to get product attributes on Product details page where user can select attributes before adding to cart.
I have two color attributes of single product in my database table. But I want to show only one color in my select box.
Product Attributes Table
Schema::create('product_attributes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('product_id');
$table->string('sku');
$table->string('size');
$table->string('color');
$table->string('price');
$table->string('stock');
$table->timestamps();
});
Relation
public function attributes()
{
return $this->hasmany('AppModelsProductAttributes', 'product_id');
}
Route
Route::get('/view-product-details/{id}', [ShopController::class, 'view_product_details']);
Function – Sending Attributes to blade file
$product_attributes = ProductAttributes::where(['product_id' => $id])->get();
Receiving Color Attributes in select box
<select class="custom-select" selected id="inputGroupSelect01" name="color">
@foreach ($product_attributes as $color)
<option value="{{$color->color}}"name="color">
{{$color->color}}
</option>
@endforeach
</select>
My Output
I know this is not looking fine. I want to show only one black color here, but I can’t.
Please help me to figure out the problem and guide me how can I resolve this.
2
Answers
You have two entries for black color. so show options with more detail like
small-002 Black
andmedium-002 Black
Try with this code
If you want to make the select consists of only the color options you can use the
groupBy()
while retrieving the product attributes see the code below:And then get the data the same as you did.