with(['otherCost' => function ($query) { $query->selectRaw('id, item as name, unit, price'); }, 'purchaseRequestOtherCostDetails' => function ($query) { $query->selectRaw('id, purchase_request_other_cost_id, unit_price_id, qty, used_qty'); $query->with(['unitPrice' => function ($query){ $query->selectRaw('id, name, unit, prices'); }]); }]) ->where('purchase_request_id', $purchaseRequestId) ->get(); } public function updateUsedQtyOtherCostDetail($createOtherCost, $otherCostDetail, $isUpdated = false){ $updt = PurchaseRequestOtherCostDetail::whereHas('purchaseRequestOtherCost', function ($q) use ($createOtherCost){ $q->where([ ['purchase_request_id', '=' , $createOtherCost->ref_pr], ['other_cost_id', '=', $createOtherCost->other_cost_id] ]); })->where('unit_price_id', $otherCostDetail->unit_price_id)->first(); $qty = $isUpdated ? $otherCostDetail->qty : (float)$updt->used_qty + (float)$otherCostDetail->qty; $updt->update([ "used_qty" => $qty ]); return $updt; } }