Reputation: 7128
I want get my product conditions as array in order to add them in cart, this is dd
of my product when I try to add it in my cart:
array:6 [▼
"id" => 4
"name" => "product four"
"price" => null
"quantity" => "1"
"attributes" => array:1 [▼
"attr" => array:2 [▼
"name" => "weight"
"value" => "45"
]
]
"conditions" => array:2 [▼
0 => CartCondition {#685 ▼ // need to add this
-args: array:4 [▼
"name" => "Black"
"value" => "10000"
"type" => "additional"
"target" => "item"
]
-parsedRawValue: null
}
1 => CartCondition {#692 ▼ // need to add this
-args: array:4 [▼
"name" => "12 inch"
"value" => "25000"
"type" => "additional"
"target" => "item"
]
-parsedRawValue: null
}
]
]
As you see unlike my
attributes
myconditions
not show just as array but get values in-args:
and-parsedRawValue: null
When I try to add product in cart I get this error:
Darryldecode \ Cart \ Exceptions \ InvalidItemException
validation.required
This is my function (how I get my conditions
and where i use them:
public function addingItem(Request $request, $id)
{
//finding product
$product = Product::findOrFail($id);
//get product weight
$weight = $product->weight;
//list of discounts
$discounts = Discount::all();
//get current time
$mytime = Carbon::now();
// get product weight in cart as attribute
$weightArray = [
'attr' => [
'name' => 'weight',
'value' => $weight,
]
];
$customAttributes = []; // my conditions comes from here
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,
'value' => $sub->price,
'type' => 'additional',
'target' => 'item',
));
array_push($customAttributes, $itemCondition1);
}
}
}
//adding product, options and conditions to cart
Cart::add(array(
'id' => $product->id,
'name' => $product->title,
'price' => $request->input('harga'),
'quantity' => $request->input('quantity'),
'attributes' => $weightArray,
'conditions' => $customAttributes, // added here
));
Session::flash('success', 'This product added to your cart successfully.');
return redirect()->back();
}
any idea why i get this error and how to fix it?
Upvotes: 0
Views: 1401
Reputation: 7128
validation issue was caused by empty price value and that was because my loop in front end while getting diffirent price on discounts time and other times, by fixing my price loop i have my product price all the time and it not return null in my function anymore.
thanks for helps.
Upvotes: 2
Reputation: 2059
if you want to convert a collection to array just use ->toarray()
Also it is a bad practice to run a query inside a foreach loop because of N + 1 query problem you may want to consider using of findMany() rather than find()
also you may want to read about array_filter too
Upvotes: 1