我尝试将产品重量放到我的购物车上,我可以得到它,但有两个问题:
It has to be add no matter user select any attribute or not.
third attribute
。这是用户选择其他属性
的时候这是我的控制器:
//finding product
$product = Product::findOrFail($id);
$weight = $product->weight; //get wight of product
// get product options in cart
$customAttributes = [];
if(!empty($request->attr)){
foreach($request->attr as $sub) {
// find the suboption
$sub = Suboption::find($sub);
if (!empty($sub->id)) {
array_push($customAttributes, [
'attr' => [
'name' => $sub->title,
'value' => $sub->price,
'weight' => $weight, // add weight to attributes
]
]);
}
}
}
//adding product and options to cart
Cart::add(array(
'id' => $product->id,
'name' => $product->title,
'price' => $product->price,
'quantity' => $request->input('quantity'),
'attributes' => $customAttributes, // attributes will add to cart in array
));
在更改bipin patel
答案的数据库后,我发现了一些变化,但我发现了另外一个问题。
这就是重量会出现在产品属性列表中,我无法将其because I only need weight for shipment calculation
分开,所以我决定将我的产品attributes
发送到conditions
并将我的体重作为我的attribute
。
在这种情况下,有两个好处:
我的产品属性价格会自动添加到购物车。 (作为条件)
我可以在没有过度循环的情况下在任何需要的地方获得体重。 (作为属性)
So here is my code now
//finding product
$product = Product::findOrFail($id);
$weight = $product->weight;
// get product options in cart
$weightArray = [
'attr' => [
'name' => 'weight',
'value' => $weight,
]
];
$customAttributes = [];
// array_push($customAttributes,$weightArray);
if(!empty($request->attr)){
foreach($request->attr as $sub) {
// find the suboption
$sub = Suboption::find($sub);
if (!empty($sub->id)) {
array_push($customAttributes, [
'name' => $sub->title,
'value' => $sub->price,
'type' => 'additional',
'target' => 'item',
]);
}
}
}
// dd($customAttributes);
//adding product and options to cart
Cart::add(array(
'id' => $product->id,
'name' => $product->title,
'price' => $product->price,
'quantity' => $request->input('quantity'),
'attributes' => $weightArray,
'conditions' => $customAttributes,
));
without choosing attributes
When I choose attributes
Here is dd of error above:
答案 0 :(得分:1)
您可以在开始if(!empty($request->attr))
喜欢:
$weightArray = ['weight'=>$weight];
$customAttributes = [];
array_push($customAttributes,$weightArray); <--- push here
if(!empty($request->attr)){
...... rest of code
添加条件更新
if(!empty($request->attr)){
foreach($request->attr as $sub) {
// find the suboption
$sub = Suboption::find($sub);
if (!empty($sub->id)) {
$itemCondition1 = new \Darryldecode\Cart\CartCondition(array(
'name' => $sub->title,
'type' => 'additional',
'target' => 'item',
'value' => $sub->price,
));
array_push($customAttributes, $itemCondition1);
}
}
}
你做这样的事情来添加条件