with(['otherCost' => function ($query) { $query->selectRaw('id, item, unit, price'); }, 'purchaseRequestOtherCostManualDetails' => function ($query) { $query->selectRaw('id, purchase_request_other_cost_manual_id, unit_price_id, qty, used_qty'); $query->with(['unitPrice' => function ($query){ $query->selectRaw('id, name, unit, prices'); }]); }]) ->where('purchase_request_id', $purchaseRequestId) ->get(); $otherCostManual->map(function ($item) { $item->purchaseRequestOtherCostManualDetails->map(function ($detail) { $detail['remaining_qty'] = (int) $detail->qty - (int) $detail->used_qty; $detail->qty_request = (float) $detail->qty; return $detail; }); return $item; }); return $otherCostManual; } public function updateUsedQtyDetail($create, $detail, $isUpdated = false) { $updt = PurchaseRequestOtherCostManualDetail::whereHas('purchaseRequestOtherCostManual', function ($q) use ($create){ $q->where([ ['purchase_request_id', '=' , $create->ref_pr], ['other_cost_id', '=', $create->other_cost_id] ]); })->where('unit_price_id', $detail->unit_price_id)->first(); $qty = $isUpdated ? (float)$detail->qty : (float)$updt->used_qty + (float)$detail->qty; $updt->update([ "used_qty" => $qty ]); } }