dimanche 4 décembre 2016

subtract quantity in session in database in laravel 5 / 5.3

I want to decrement the quantity of my product in database when I accept the order. Help me please.

This is my Cart.php / Session

<?php
namespace App;
class Cart
{
public $items = null;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart)
{
    if ($oldCart) {
        $this->items = $oldCart->items;
        $this->totalQty = $oldCart->totalQty;
        $this->totalPrice = $oldCart->totalPrice;
    }
}
public function add($item, $id) {
    $storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
    if ($this->items) {
        if (array_key_exists($id, $this->items)) {
            $storedItem = $this->items[$id];
        }
    }
    $storedItem['qty']++;
    $storedItem['price'] = $item->price * $storedItem['qty'];
    $this->items[$id] = $storedItem;
    $this->totalQty++;
    $this->totalPrice += $item->price;
}
public function reduceByOne($id) {
    $this->items[$id]['qty']--;
    $this->items[$id]['price'] -= $this->items[$id]['item']['price'];
    $this->totalQty--;
    $this->totalPrice -= $this->items[$id]['item']['price'];
    if ($this->items[$id]['qty'] <= 0) {
        unset($this->items[$id]);
    }
}
public function removeItem($id) {
    $this->totalQty -= $this->items[$id]['qty'];
    $this->totalPrice -= $this->items[$id]['price'];
    unset($this->items[$id]);
}
}

And My ProductController, where i will save the session in database. It works.

    public function getCheckout()
{
    if (!Session::has('cart')) {
        return view('order.shopping-cart');
    }
    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    $total = $cart->totalPrice;
    return view('customer.shopping-cart', ['total' => $total]);
}

public function postCheckout(Request $request)
{
    if (!Session::has('cart')) {
        return redirect()->route('order.shoppingCart');
    }

    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    $total = $cart->totalPrice;
        $order = new Order;
        $order->cart = base64_encode(serialize($cart));
        //$order->totalAmmount = $total;
        Auth::guard('customer')->user()->orders()->save($order);
    Session::forget('cart');
    return redirect()->route('order.shoppingCart');
}

And this is the admin side controller, where I will accept the order. And I want to decrement the quantity when I Accept. How can I do that?

Here's the code.

    public function accepted(Order $order){
        $order->status = true;
        $order->update(['accepted' => $order->status]);
        foreach($order->cart as $item){
            $product = Medicine::find($item->id);
            $product->decrement('stock', $item->qty);
        return redirect()->route('manage-order.index')->with('message', 'Order accepted.');
    } 
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2h21AhV
via IFTTT

Aucun commentaire:

Enregistrer un commentaire