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('App\Models\ProductAttributes', '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 selected id="inputGroupSelect01" name="color">
@foreach ($product_attributes as $color)
<option value="{{$color->color}}"name="color">
{{$color->color}}
</option>
@endforeach
</select>
My output Click to show image
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.
CodePudding user response:
You have two entries for black color. so show options with more detail like small-002 Black
and medium-002 Black
Try with this code
<select selected id="inputGroupSelect01" name="color">
@foreach ($product_attributes as $color)
<option value="{{ $color->id }}" name="color">
{{$color->sku .' '.$color->color}}
</option>
@endforeach
</select>
CodePudding user response:
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:
$product_attributes = ProductAttributes::select("color")->where(['product_id' => $id])->groupBy("color")->get();
And then get the data the same as you did.
<select selected id="inputGroupSelect01" name="color">
@foreach ($product_attributes as $color)
<option value="{{$color->color}}"name="color">
{{$color->color}}
</option>
@endforeach
</select>