validate([ 'name' => 'required|string|max:255|unique:units,name', 'code' => 'nullable|string|max:50', ], [ 'name.required' => '單位名稱為必填項目', 'name.unique' => '該單位名稱已存在', 'name.max' => '單位名稱不能超過 255 個字元', 'code.max' => '單位代碼不能超過 50 個字元', ]); Unit::create($validated); return redirect()->back()->with('success', '單位已建立'); } /** * Update the specified resource in storage. */ public function update(Request $request, Unit $unit) { $validated = $request->validate([ 'name' => 'required|string|max:255|unique:units,name,' . $unit->id, 'code' => 'nullable|string|max:50', ], [ 'name.required' => '單位名稱為必填項目', 'name.unique' => '該單位名稱已存在', 'name.max' => '單位名稱不能超過 255 個字元', 'code.max' => '單位代碼不能超過 50 個字元', ]); $unit->update($validated); return redirect()->back()->with('success', '單位已更新'); } /** * Remove the specified resource from storage. */ public function destroy(Unit $unit) { // Check if unit is used in any product $isUsed = Product::where('base_unit_id', $unit->id) ->orWhere('large_unit_id', $unit->id) ->orWhere('purchase_unit_id', $unit->id) ->exists(); if ($isUsed) { return redirect()->back()->with('error', '該單位已被商品使用,無法刪除'); } $unit->delete(); return redirect()->back()->with('success', '單位已刪除'); } }