validate([ 'count' => ['required', 'integer', 'min:0'], 'section_id' => ['required', 'integer'], // 'mapping_id' => ['required', 'integer'], ]); $entry = StockEntry::with('sections') ->whereHas('sections', function($q) use ($data) { $q->where('section_id', $data['section_id']); }) ->first(); // 1) Update the pivot table count for this section $entry->sections()->updateExistingPivot($data['section_id'], [ 'count' => $data['count'], ]); // 2) Recalculate the total across all sections and save it on the entry // (assuming you want `stock_entries.count` to always equal the sum of its section counts) $total = $entry->sections() ->get() // pull fresh pivot data ->sum(fn($sec) => $sec->pivot->count); $entry->count = $total; $entry->save(); return response()->json([ 'message' => 'Section count and entry total updated', 'data' => $entry->load('sections'), ]); } public function getItems(Request $request) { // Get physical items from warehouse DB $physicalItems = PhysicalItem::select('id', 'name') ->where('name', 'like', '%' . $request->input('item_name', '') . '%')->limit(100) ->get(); return response()->json([ 'physicalItems' => $physicalItems, ]); } }