I want to decrease quantity from products table when order is added to cart ,right now when I add something to cart, correct quantity is not decreasing. For example if a I place order of 6 items then a random amount gets decreased from my products table.
Here is my code in order controller of livewire:
public function IncrementQty($cartId)
{
$carts=Cart::find($cartId);
$carts->increment('product_qty',1);
$updatePrice=$carts->product_qty * $carts->product->price;
$carts->update(['product_price'=>$updatePrice]);
$getProductStock=Product::where(['id'=>$carts['product_id']])->first()->toArray();
$newStock=$getProductStock['quantity'] - $carts['product_qty'];
Product::where(['id'=>$carts['product_id']])->update(['quantity'=>$newStock]);
$this->mount();
}
Being a beginner I am unable to understand about what's wrong here. Should I be substracting it from orderDetails table instead of carts table? If yes then how?
CodePudding user response:
it seems you have a problem in this line:
$newStock=$getProductStock['quantity'] - $carts['product_qty'];
$carts is an object not an array, so, do:
$newStock = $getProductStock['quantity'] - $carts->product_qty;
CodePudding user response:
A couple of things to note first,
You should not call
$this->mount()
or any other lifecycle hooks from Livewire. If there are code inside your mount-method you need to run again, then abstract it into a separate method, and call it from both yourmount()
method and yourIncrementQty()
method.You can use model-route-binding to inject the correct model into the method
public function IncrementQty(Cart $cart)
You can then simplify your code by using the product
relation on the cart directly, and calling decrement()
on that.
public function IncrementQty(Cart $cart)
{
$product = $cart->product;
$cart->increment('product_qty', 1);
$cart->update(['product_price' => $cart->product_qty * $product->price]);
$product->decrement('quantity', 1);
$this->mount(); // Do not call mount manually, abstract the contents you need into a separate method instead
}
If you are still experiencing issues, then it cannot possibly be this piece of code, or you are misreading your data somehow - in any case, if you are still experiencing issues, you will need to provide additional information with your table-structure, models, how you call this method, and data before and after your actions.