Laravel中保存/生成账单时实现库存扣减的技术求助
Hey there! Let's work through adding inventory deduction functionality when saving your bills. Your current code saves customer data and sales records, so we'll integrate the Stock model updates right into that flow, with safeguards to keep your data consistent.
Key Improvements to Add
- Use database transactions to make sure customer data, sales records, and inventory changes all succeed or fail together (no partial updates!)
- Check for sufficient stock before deducting to avoid negative inventory
- Handle exceptions gracefully to roll back changes if something goes wrong
Modified Code with Inventory Deduction
public function addBill(Request $request) { // Optional: Uncomment validation to ensure required fields are present // $this->validate($request,[ // 'cus_id_no' => 'required', // 'productname' => 'required|array', // 'qty' => 'required|array' // ]); // Start a database transaction to ensure atomicity DB::beginTransaction(); try { $customer = new Customer; $customer->cus_id_no = $request->cus_id_no; $customer->name = $request->name; $customer->p_number = $request->p_number; $customer->address = $request->address; $customer->cus_type = $request->cus_type; $customer->total = $request->total; $customer->tax = $request->tax; $customer->g_total = $request->g_total; $customer->paid = $request->paid; $customer->remaining = $request->g_total - $request->paid; $customer->save(); $customerId = $customer->id; foreach($request->productname as $key=>$productId) { $quantitySold = $request->qty[$key]; // Fetch the corresponding stock record for the product $stock = Stock::where('pro_id', $productId)->first(); // Validate stock availability if (!$stock || $stock->quantity < $quantitySold) { throw new \Exception("Insufficient stock for product ID: $productId"); } // Deduct the sold quantity from inventory $stock->quantity -= $quantitySold; $stock->save(); // Insert the sale record as before $saleData = array( 'cus_id' => $customerId, 'pro_id' => $productId, 'actual_cost' => $request->actual_cost[$key], 'qty' => $quantitySold, 'price' => $request->price[$key], 'dis' => $request->dis[$key], 'amount' => $request->amount[$key] ); Sale::insert($saleData); } // Commit all changes if everything runs smoothly DB::commit(); return redirect()->back()->with('success', 'Bill saved successfully, inventory updated!'); } catch (\Exception $e) { // Roll back all changes if any error occurs DB::rollBack(); return redirect()->back()->with('error', "Failed to save bill: " . $e->getMessage()); } }
Notes on the Changes
- Transaction Safety: The
DB::beginTransaction(),DB::commit(), andDB::rollBack()methods ensure that if any step fails (like insufficient stock), none of the data gets saved—keeping your database consistent. - Stock Validation: We check that the stock exists and has enough quantity before making deductions. If not, we throw an error and undo all pending changes.
- Error Handling: The try/catch block catches exceptions and returns a user-friendly error message, so you and your users know exactly what went wrong.
Just make sure your Stock model uses the correct column name for quantity (adjust $stock->quantity to match your actual column name if it's different, like qty). Also, don't forget to uncomment and tweak the validation rules to match your required input fields—this helps catch bad data early!
内容的提问来源于stack exchange,提问作者Robert Williams
相关产品推荐
相关产品推荐

