Laravel E-Commerce Project - Show Product Attribute on Cart Page
In this video, we will learn how to display product attributes on the cart page.
Let's start by opening the DetailsComponent.php class file and creating a property:
public $satt=[];
Next, open the details-component.blade.php view file and bind the property to the select control:
<div>
@foreach($product->attributeValues->unique('product_attribute_id') as $av)
<div class="row" style="margin-top: 20px">
<div class="col-xs-2">
<p>{{$av->productAttribute->name}}</p>
</div>
<div class="col-xs-10">
<select class="form-control" style="width: 200px" wire:model="satt.{{$av->productAttribute->name}}">
@foreach($av->productAttribute->attributeValues->where('product_id',$product->id) as $pav)
<option value="{{$pav->value}}">{{$pav->value}}</option>
@endforeach
</select>
</div>
</div>
@endforeach
</div>
Now, go back to the DetailsComponent class file and add the following code to the store function:
public function store($product_id,$product_name,$product_price)
{
Cart::instance('cart')->add($product_id,$product_name,$this->qty,$product_price,$this->satt)->associate('App\Models\Product');
session()->flash('success_message','Item added in Cart');
return redirect()->route('product.cart');
}
Then, open the cart-component.blade.php file and display the product's selected attributes. Add the following code after the product name:
@foreach($item->options as $key=>$value)
<div style="vertical-align:middle; width:180px;">
<p><b>{{$key}}: {{$value}}</b></p>
</div>
@endforeach
That's it! Let's test the functionality. Switch to the browser and refresh the page. Open any product, select the attributes (e.g., color and size), and add it to the cart.
After adding the product to the cart, you should see the product's attributes displayed. Try adding another product to the cart with different attributes, and you should see both products with their respective attributes.
By following these steps, you can display product attributes on the cart page.