I'm using a Laravel 8 with darryldecode/laravelshoppingcart Cart Package. I'm struggling a bit with updating product quantity if it exists in users cart.
For example: If cart is empty, while adding a product and then clicking mutliple times on "Add To Cart" it adds only one product and then updates quantity to its maximum. But when I'm adding a second product, and then adding again product 1 it adds another product to the cart. It definitely should not add another product but it has to be restricted to maximum quantity of first product.
My cart store method:
public function store(CartStoreRequest $request) {
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = uniqid();
$userID = $validated['user_id'];
// get current user cart
$currentCart = \Cart::session($userID);
if(!empty($currentCart->getContent()->toArray())) {
foreach($currentCart->getContent() as $item) {
$productID = $item->associatedModel->id;
if($productID === $product->id) {
$currentCart->update($item->id, [
'quantity' => [
'relative' => false,
'value' => $product->minStock($item->quantity + $validated['quantity']),
]
]);
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
}
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
return redirect()->back();
}
I hope that's someone had similar problem and knows how to solve this.
Okay, so the solution is to use product ID as $rowId,
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = $product->id;
$userID = $validated['user_id'];
$currentCart = \Cart::session($userID);
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $product->minStock($validated['quantity']),
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
$currentCartContents = $currentCart->get($rowId);
$quantity = $product->minStock($currentCartContents->quantity);
if($currentCartContents->quantity !== $quantity) {
$currentCart->update($rowId, [
'quantity' => [
'relative' => false,
'value' => $quantity,
]
]);
}
return redirect()->back();
Related
i want to extends my custom entity from WC_Order_Item_Product. i add my custom extra data to this class .
class RoomOrderItem extends OrderItemLegacy {
protected $extra_data = array(
'product_id' => 0,
'variation_id' => 0,
'quantity' => 1,
'tax_class'=> '',
'subtotal' => 0,
'subtotal_tax' => 0,
'total' => 0,
'total_tax' => 0,
'taxes' => [
'subtotal' => [],
'total' => [],
],
'period' => '',
'extra' => '',
'manager' => [],
'entity' => __CLASS__,
);
public function set_period(DateTime $day){
$this->set_prop('period',$day->format('Y-m-d'));
return $this;
}
public function set_extra(int $extra){
$this->set_prop('extra',$extra);
return $this;
}
public function set_manager(array $manager){
$this->set_prop('manager',$manager);
return $this;
}
}
but when is adding my custom order item (RoomOrderItem extends WC_Order_Item_Product) new extra data does not save in any tables. here is my sample code for adding new RoomOrdeItem to order object:
public function add(RoomCartItem $room_cart_item){
$this->set_props([
'quantity' => $room_cart_item->get_prop('quantity'),
'variation' => $room_cart_item->get_prop('variation'),
'subtotal' => $room_cart_item->get_prop('line_subtotal'),
'total' => $room_cart_item->get_prop('line_total'),
'name' => $room_cart_item->get_hotel()->get_name(),
'product_id' => $room_cart_item->get_prop('product_id'),
'variation_id' => $room_cart_item->get_prop('variation_id'),
'_period' => $room_cart_item->get_period(),
'_manager' => $room_cart_item->get_manager(),
'_extra' => $room_cart_item->get_extra(),
'_entity' => __CLASS__,
]);
return $this->get_order()->add_item($this);
}
In addition, I know that a meta can be added to this item with the $this->add_meta_data(). But why the new data is not automatically saved in the item.
I think your issues is you haven't saved the data.
if you're working with an orderitem object class you should be able to use the save() function.
public function add(RoomCartItem $room_cart_item){
$this->set_props([
'quantity' => $room_cart_item->get_prop('quantity'),
'variation' => $room_cart_item->get_prop('variation'),
'subtotal' => $room_cart_item->get_prop('line_subtotal'),
'total' => $room_cart_item->get_prop('line_total'),
'name' => $room_cart_item->get_hotel()->get_name(),
'product_id' => $room_cart_item->get_prop('product_id'),
'variation_id' => $room_cart_item->get_prop('variation_id'),
'_period' => $room_cart_item->get_period(),
'_manager' => $room_cart_item->get_manager(),
'_extra' => $room_cart_item->get_extra(),
'_entity' => __CLASS__,
]);
$this->save(); //save the updated props
return $this->get_order()->add_item($this);
}
I am working on partials payments by creating order programmatically.
I am stuck with the issue when I am doing partials payments of a product in order. I created the order total successfully but woo commerce add remaining amount as a coupons, whereas I did not any coupons.
Here is my Function:
public function createNewOrder($order_array){
$address = array(
'first_name' => $order_array['first_name'],
'last_name' => $order_array['last_name'],
'company' => $order_array['company'],
'email' => $order_array['email'],
'phone' => $order_array['phone'],
'address_1' => $order_array['address_1'],
'address_2' => $order_array['address_2'],
'city' => $order_array['city'],
'state' => $order_array['state'],
'postcode' => $order_array['postcode'],
'country' => $order_array['country']
);
$args = array(
'customer_id' => $order_array['customer_id'],
'status' => $order_array['order_status'],
);
$order = wc_create_order($args);
$productArray = json_decode(stripslashes($order_array["productArray"]), true);
// This is an existing SIMPLE product
foreach ($productArray as $key => $value) {
$itemData=$value['id'];
$wc_deposit_enabled = get_post_meta( $itemData, '_wc_deposit_enabled', true );
$wc_deposit_amount = get_post_meta( $itemData, '_wc_deposit_amount', true );
$wc_amount = get_post_meta( $itemData,'_price',true );
if ($wc_deposit_enabled!="") {
$order->add_product( get_product($itemData), $value['quantity'], array(
'totals' => array(
'subtotal' => $wc_amount,
'total' => $wc_deposit_amount,
'subtotal_tax' => 0,
'tax' => 0,
)));
[enter image description here][1]
}else{
$order->add_product( get_product($itemData), $value['quantity']);
}
}
if(!empty($order_array['order_status']))
{
$order->update_status($order_array['order_status']);
}
$order->set_address( $address, 'billing' );
$order->calculate_totals();
$order->save();
}
How do I update the two tables, I have 2 tables, order and product, I want to update the product data on the order, I do it with the following code, but the product doesn't want to update
public function update(Request $request, $id , Product $product)
{
$request->validate([
'do_code' => 'required',
'delivery_date' => 'required',
'qty' => 'required',
'user_id' => 'required',
'customer_id' => 'required',
'armada_id' => 'required',
'send_from_id' => 'required',
]);
$data = Delivery_order::find($id);
$data->update($request->all());
if (count($request->product_name) > 0) {
foreach ($request->product_name as $item => $v) {
$data2 = array(
'order_id' => $id,
'product_name' => $request->product_name[$item],
'qty' => $request->qty[$item],
'tonise' => $request->tonise[$item]
);
$product->update($data2);
}
}
return redirect('/do')->with('success', 'Data Successfully Updated');
}
Use just like this
$product->order_id = $id,
$product->product_name = $request->product_name[$item],
$product->qty = $request->qty[$item],
$product->tonise = $request->tonise[$item]
$product->save();
I think, you can use Laravel Relationship to update the second table.
I am working with Codeigniter cart
my problem is how to update the quantity of items if the item is already exist in the cart.
My model
function addToCart(){
$data = array(
'id' => $this->input->post('product_id'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'name' => $this->input->post('product_name'),
);
$this->cart->insert($data);
redirect(base_url().'shopping-cart-view');
}
This may help:
function addToCart(){
$data = array(
'id' => $this->input->post('product_id'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'name' => $this->input->post('product_name'),
);
/* modification starts */
$db_query = $this->db->get_where('cart', $data) ;
$rows = $query->num_rows();
if($rows > 0){
// update the record
}else{
//insert record..
}
// modification ends
redirect(base_url().'shopping-cart-view');
}
Hi I have a cart in Codeigniter that works well. I tried to look for a discount/coupon handling but can't.
This is my cart code:
public function addToCart($id){
$this->load->model('products_model');
$products = $this->products_model->getItemDetail($id);
foreach ($products as $product) {
$insert = array(
'id' => $product->id,
'name' => $product->name,
'qty' => '1',
'price' => $product->item_eur,
'image' => $product->image,
'options' => array(
'info' => $product->cart_description,
'qty_description' => $product->qty_description
)
);
$this->cart->insert($insert);
}
$last = end($this->cart->contents());
echo $last['rowid'];
}
I thought of making a Coupon Code read from the DB and insert a discount as an item in the cart:
public function addCoupon(){
$this->load->model('products_model');
$res = $this->products_model->getCoupon($_POST['value']);
if($res){
foreach($res as $result){
$coupon = array(
'id' => $result->id,
'name' => $result->name,
'qty' => '1',
'price' => $result->discount,
'options' => array(
'info' => 'coupon',
'qty_description' => ''
)
);
$this->cart->insert($coupon);
}
echo '1';
}else{
$this->lang->load('products');
echo $this->lang->line('cart_notok');
}
}
Where the DB is
[name:type] (example)
id:int (1)
name: varchar ('Discount of 20€')
code: varchar ('AFD1234')
discount: decimal (-20)
[Edit]
And the model:
public function getCoupon($code){
$results = $this->db->get_where('coupons', array('code' => $code));
return $results->result();
}
The item gets added to the cart but if the 'price' => $result->discount is set to -20 or a percentage it gets set as +20€ and not -20€.
Any way to do this?