Decrease product quantity in database after order is placed with Laravel

落爺英雄遲暮 提交于 2020-01-23 13:09:59

问题


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.


回答1:


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.




回答2:


For those using resource controller or a simpler/easy answer:

public function create()
{
    $stocks = Stock::all();
    //dd($stocks);
    return view('sales.create', compact('stocks'));
    //$sales = Sale::pluck('stock_id')->prepend('stock_id');
    //$sales = DB::table('stocks')->select('stock_id')->get();
    //return view('sales.create')->with('sales',$sales);
}


public function store(Request $request)
{
    $this->validate($request, [
        'stock_id' => 'required',
        'product_name' => 'required',
        'sale_quantity' => 'required',
        'unit_selling_price' => 'required',
        'total_sales_cost' => 'required'
        ]);

    //create stock
    $sale = new Sale;
    $sale->stock_id = $request->input('stock_id');
    $sale->product_name = $request->input('product_name');
    $sale->sale_quantity = $request->input('sale_quantity');
    $sale->unit_selling_price = $request->input('unit_selling_price');
    $sale->total_sales_cost = $request->input('total_sales_cost');
    $sale->stock_quantity =
        $sale->save();
    DB::table('stocks')->where('stock_name', $request->input('product_name'))->decrement('stock_quantity', $request->input('sale_quantity'));

    return redirect('/sales')->with('success', 'Sale Saved');
}


来源:https://stackoverflow.com/questions/39593304/decrease-product-quantity-in-database-after-order-is-placed-with-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!