Search code examples
phpmysqllaravel-4cart

Decrease product quantity in database after order is placed with Laravel


I have cart on the site and so far everything work perfectly. Now I'm trying to make quantity for each product which admin can add in backend ( already done ) and when customer order product(s) to decrease quantity in database.

So far as I said admin panel is ready and can add quantity to product which is saved in database. Here is my cart submit controller

public function orderSubmit() {
    $cart = Session::get(self::CART_SESSION_KEY, array());
    if (count($cart) < 1) {
        return Redirect::to('/');
    }

    $validatorRules = array(
        'captcha' => 'required|captcha'      
    );

    Input::merge(array_map('trim', Input::all()));
    $validator = Validator::make(Input::all(), $validatorRules);

    if ($validator->fails()) {
        return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $order = new Order();
    $order->user_id = self::$user->user_id;
    $order->data = json_encode($cart, true);
    $order->info = Input::get('additional_info');

    $order->save();
    Session::put(self::CART_SESSION_KEY, array());

    return Redirect::to('/)->with('message_success', 'Order created! We will contact you shortly to confirm your order details.');
}

The cart is saved in $order->data = json_encode($cart, true); and in database information for product(s) etc look

{"title":"Test Product","description":"You save 25%","quantity":1,"price":135}

If there are multiple products in order above array will have also them.

What I can't understand is how to extract which product is ordered and how many pieces from it so I can later update database quantity field for each product?

I don't even know from where to start.


Solution

  • Assuming $cart is an array and based on the json you provided, you'll need to:

    1. Add the product id to the $cart otherwise it will be pretty much impossible to know what are the products for that order
    2. With the product id for each product on the $cart, you can now loop the cart products and update them. Something like the following code.

      public function orderSubmit() {
          $cart = Session::get(self::CART_SESSION_KEY, array());
          if (count($cart) < 1) {
              return Redirect::to('/');
          }
      
          $validatorRules = array(
              'captcha' => 'required|captcha'      
          );
      
          Input::merge(array_map('trim', Input::all()));
          $validator = Validator::make(Input::all(), $validatorRules);
      
          if ($validator->fails()) {
              return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($validator->errors())->withInput(Input::except(['captcha']));
          }
          \DB::beginTransaction();
      
          try {
              $order = new Order();
              $order->user_id = self::$user->user_id;
              $order->data = json_encode($cart, true);
              $order->info = Input::get('additional_info');
      
              $order->save();
      
              foreach ($cart as $item) {
                  $product = Product::find($item->id);
                  $product->decrement('votes', $item->quantity);
              }
      
              Session::put(self::CART_SESSION_KEY, array());
      
              \DB::commit();
      
              return Redirect::to('/')->with('message_success', 'Order created! We will contact you shortly to confirm your order details.');
          } catch (\Exception $ex) {
              \DB::rollback();
      
              return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($ex->getMessage())->withInput(Input::except(['captcha']));
          }
      }
      

    I added the code for the transaction to assure the quantity is decreased when the order is stored correctly.