我的代码如下,我的产品属性将被选中并添加到购物车
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
问题是,如果我的产品没有任何属性可供选择,那么在尝试将产品添加到购物车时会出现错误。所以我尝试做类似下面的代码,但我得到了这个错误:
解析错误:语法错误,意外'{'
if(!empty($product->suboptions){
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
}
任何想法?
修复if
语句后,我在'attributes' => $customAttributes,
未定义的变量:customAttributes
这是我的完整代码
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();
}
答案 0 :(得分:2)
您在if
声明中缺少结束括号。
您的错误消息提示此处有一个语法错误 - 特别是意外的{
。
排除故障的第一步是按照您的代码查找每个{
并检查前面的代码,因为前面的代码中存在导致错误的内容。如果您在上面的代码中发现一切正常,那么请转到下一个{
。
if(!empty($product->suboptions){
应为if(!empty($product->suboptions)){
。
整体而言:
if(!empty($product->suboptions)){
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
}
更新地址编辑
同样,错误提示是变量$customAttributes
不存在。
让我们看一下$ customAttributes的范围:
if(!empty($product->suboptions)){
foreach($product->suboptions as $subs) {
$customAttributes[] = [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
];
}
}
每次循环遍历products子选项时,都声明$customAttributes
并且它仅存在于循环的迭代中。继续这一点,一旦你离开for循环,$customAttributes
就不复存在了。
因此,当您尝试在$customAttributes
模型上使用时,会出现Cart
是未定义变量的错误。
要解决此问题,请在for循环外指定$customAttributes
,并在循环的每次迭代时推送到数组。有点像这样:
$customAttributes = [];
if(!empty($product->suboptions)){
foreach($product->suboptions as $subs) {
array_push($customAttributes, [
'attr' => [
'label' => $subs->title,
'price' => $subs->price,
]
);
}
}