/**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     try {
         $user = JWTAuth::parseToken()->authenticate();
         if ($user) {
             $data = ['product_code' => $request->product_code];
             $des = ['name' => $request->name, 'price' => $request->price];
             $productCollection = Product::where($data)->get();
             $product_des = new ProductDescription($des);
             if ($productCollection->isEmpty()) {
                 //if collection not exist mean there is no entry of the productCode before
                 $product = new Product($data);
                 $product->save();
                 $product_des->product()->associate($product);
             } else {
                 //since collection have some data get the product code from before n use it
                 $product = $productCollection[0];
                 //check if user already have the product with this product code
                 $array1 = $user->product_descriptions;
                 $array2 = $product->product_descriptions;
                 if (!$array1->intersect($array2)->isEmpty()) {
                     ///if there is an instance of product description in it return error with msg in json
                     return response()->json(['message' => 'Error Product Existed']);
                 }
                 $product_des->product()->associate($product);
             }
             $user->product_descriptions()->save($product_des);
             $message = ["message" => "Product Submitted"];
             return json_encode($message);
         }
     } catch (JWTException $e) {
     }
     return response("Invalid User", 401);
 }
Exemplo n.º 2
0
 function addProductDescription($user, $productCodeArray, $productDescriptionData)
 {
     $product = Product::firstOrCreate($productCodeArray);
     $productDescription = new ProductDescription($productDescriptionData);
     $productDescription->product()->associate($product);
     $user->product_descriptions()->save($productDescription);
 }