all(), [ 'page' => 'integer|min:1', 'limit' => 'integer|min:1|max:100', 'name' => 'string|nullable', ]); if ($validator->fails()) { return $this->error(422, '参数错误', $validator->errors()); } $query = Supplier::query(); if ($request->filled('name')) { $query->where('name', 'like', "%{$request->name}%"); } $list = $query->paginate($request->input('limit', 10)); return $this->success([ 'list' => $list->items(), 'total' => $list->total(), 'current_page' => $list->currentPage(), 'last_page' => $list->lastPage(), ]); } /** * 供应商详情 */ public function show($id) { $supplier = Supplier::find($id); if (!$supplier) { return $this->error(404, '供应商不存在'); } return $this->success($supplier); } /** * 创建供应商 */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'code' => 'required|string|unique:suppliers,code', 'name' => 'required|string|max:255', 'contact' => 'nullable|string|max:100', 'phone' => 'nullable|string|max:20', 'address' => 'nullable|string|max:500', 'remark' => 'nullable|string', ]); if ($validator->fails()) { return $this->error(422, '参数错误', $validator->errors()); } $supplier = Supplier::create($request->all()); return $this->success($supplier, '创建成功', 201); } /** * 更新供应商 */ public function update(Request $request, $id) { $supplier = Supplier::find($id); if (!$supplier) { return $this->error(404, '供应商不存在'); } $validator = Validator::make($request->all(), [ 'code' => 'sometimes|string|unique:suppliers,code,' . $id, 'name' => 'sometimes|string|max:255', 'contact' => 'nullable|string|max:100', 'phone' => 'nullable|string|max:20', 'address' => 'nullable|string|max:500', 'remark' => 'nullable|string', ]); if ($validator->fails()) { return $this->error(422, '参数错误', $validator->errors()); } $supplier->update($request->all()); return $this->success($supplier, '更新成功'); } /** * 删除供应商 */ public function destroy($id) { $supplier = Supplier::find($id); if (!$supplier) { return $this->error(404, '供应商不存在'); } $supplier->delete(); return $this->success(null, '删除成功'); } /** * 获取所有供应商(下拉选择) */ public function all() { $list = Supplier::select('id', 'name', 'code')->get(); return $this->success($list); } // 统一响应方法(可放在基类 Controller,这里临时放置) private function success($data = null, $message = 'success', $code = 200) { return response()->json([ 'code' => $code, 'data' => $data, 'message' => $message ], $code); } private function error($code, $message, $errors = null) { $response = [ 'code' => $code, 'message' => $message, ]; if ($errors) { $response['errors'] = $errors; } return response()->json($response, $code); } }