Example #1
0
 public function store(Request $request)
 {
     $data = array_only($request->json()->all(), ['product_id', 'sku', 'quantity']);
     $stock = ProductStock::whereSku($data['sku'])->firstOrFail();
     if ($stock->stocks < $data['quantity']) {
         throw new \Exception('stock not enough');
     }
     $data['access_token'] = $request->headers->get('authorization');
     $data['user_id'] = $request->user->id;
     $bag = Bag::firstOrNew(array_except($data, ['user_id', 'quantity']));
     if ($bag->exists) {
         if ($stock->stocks < $data['quantity']) {
             throw new \Exception('stock not enough');
         }
         $bag->quantity += $data['quantity'];
     } else {
         $bag->quantity = $data['quantity'];
     }
     $bag->user_id = $data['user_id'];
     $bag->save();
     return response()->created($bag);
 }