skip to Main Content

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.

Click to show image

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

enter image description here

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


  1. 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 class="custom-select" selected id="inputGroupSelect01" name="color">
        @foreach ($product_attributes as $color)
            <option value="{{ $color->id }}" name="color">
                {{$color->sku .' '.$color->color}}
            </option>
        @endforeach
    </select>
    
    Login or Signup to reply.
  2. 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 class="custom-select" selected id="inputGroupSelect01" name="color">
     @foreach ($product_attributes as $color)
    
       <option value="{{$color->color}}"name="color">
        {{$color->color}}
      </option>
    
     @endforeach
    </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search