request->add(['customer_id'=>auth('customer')->id()]); $model = PriceTrigger::class; $this->with = ['customer']; $this->select = ['*']; $this->search = ['*']; parent::__construct($model, $this->with, $this->select); } /** * Display a listing of the resource. * * @return \Illuminate\Http\JsonResponse */ public function index() { $query = PriceTrigger::where("customer_id", auth()->id()); if (PriceTrigger::hasProductIdColumn()) { $query->with(['product:id,title']); } return response()->json($query->get()); } public function store(Request $request) { $this->sanitizeProductId($request, true); $request->merge(['action' => 'sms']); return parent::store($request); } public function update(Request $request, $id) { $this->sanitizeProductId($request, false); $request->merge(['action' => 'sms']); return parent::update($request, $id); } private function sanitizeProductId(Request $request, bool $required): void { if (! PriceTrigger::hasProductIdColumn()) { $request->request->remove('product_id'); return; } $productId = $this->normalizeProductId($request->input('product_id')); if ($productId === null) { if ($required) { throw new UnprocessableEntityHttpException('محصول را انتخاب کنید'); } $request->request->remove('product_id'); return; } $exists = Product::query() ->where('id', $productId) ->where('active', 1) ->exists(); if (! $exists) { throw new UnprocessableEntityHttpException('محصول نامعتبر است'); } $request->merge(['product_id' => $productId]); } private function normalizeProductId($productId): ?int { if (is_array($productId)) { $productId = $productId['id'] ?? $productId['product_id'] ?? null; } if (is_object($productId)) { $productId = $productId->id ?? null; } if ($productId === null || $productId === '' || ! is_numeric($productId)) { return null; } $id = (int) $productId; return $id > 0 ? $id : null; } }