with=[]; $select = ['*']; $search=['name']; $request->request->add(['customer_id'=>auth('customer')->id()]); $query = OfferCode::with($this->with)->where('customer_id',auth('customer')->id()); parent::__construct($model, $this->with/*, $select, null,$query,$search*/); } public function store(Request $request) { $data = $request->all(); if (OfferCode::where('code',$data['code'])->first()) { return response()->json(['message' => 'این کد تخفیف از قبل ثبت شده'], 422); } $user = OfferCode::create($data); return $this->resultCreate($user->id); } public function check_code(Request $request) { $data = $request->all(); // Check if the code is provided if (!isset($data['code'])) { return response()->json(['message' => 'کد تخفیف اجباریه'], 422); } // Find the offer code, or return error if not found if (!$OfferCode = OfferCode::where('code', $data['code'])->first()) { return response()->json(['message' => 'کد تخفیف پیدا نشد'], 422); } // Check if items are provided if (!isset($data['items']) || !is_array($data['items'])) { return response()->json(['message' => 'لیست محصولات اجباری است'], 422); } // Retrieve products and apply discount $select = ['*', // Product::$SELECT_CAJ, // Product::$SELECT_GENDER_STR, ]; $items = Product::with([ // 'collection', 'file', // 'gallery.file', // 'brand.image' ])->select($select)->whereIn('id',$data['items'])->get(); $i=0; foreach ($items as $i => $row) { // Apply percentage or fixed discount if (!empty($OfferCode->discount_percent)) { // Apply percentage discount $newPrice = $row->price - ($row->price * $OfferCode->discount_percent / 100); } else { // Apply fixed price discount $newPrice = $row->price - $OfferCode->discount_price; } // Ensure the discounted price doesn't go below zero $newPrice = max(0, $newPrice); // Update the price_with_discount field $row->price_with_discount = $newPrice; // Convert model to an array and assign the discounted values $response[$i] = $row->toArray(); $response[$i]['price_with_discount'] = $newPrice; $response[$i]['discount'] = $row->price - $newPrice; } // Return the updated items with the discount applied return response()->json($response); } }