I have code below where my product attributes will be select and add to cart
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
the problem is if my product doesn't have any attribute to choose i will get error while trying to add product to cart. So I tried to do something like code below but i get this error:
Parse error: syntax error, unexpected '{'
if(!empty($product->suboptions){
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
}
any idea?
Update
after fixing if
statement i get this error on 'attributes' => $customAttributes,
Undefined variable: customAttributes
here is my full code
public function addingItem($id)
{
$product = Product::where('id', $id)->firstOrFail();
if(!empty($product->suboptions)){
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
}
Cart::add(array(
'id' => $product->id,
'name' => $product->title,
'price' => $product->price,
'quantity' => 1,
'attributes' => $customAttributes,
));
Session::flash('success', 'This product added to your cart successfully.');
return redirect()->back();
}