['required','integer', new Exists(ProductCategoryModel::class,'id')], 'supplier_id' => ['nullable','integer', 'exclude_if:supplier_id,0', new Exists(SupplierModel::class,'id')], 'market' => 'nullable|string|max:50', 'name' => 'required|string|max:100', 'spec' => 'nullable|string|max:100', 'unit' => 'nullable|string|max:20', 'image_ids' => 'nullable|array|max:255', 'image_ids.*' => ['integer', new Exists(SysFileModel::class, 'id')], 'content' => 'nullable|string', 'sort' => 'nullable|integer', 'shelf_life' => 'nullable|integer|min:0', 'stock' => 'nullable|integer|min:0', 'status' => 'nullable|integer|in:0,1', 'cost_price' => 'nullable|numeric|min:0|max:99999999', 'remark' => 'nullable|string|max:255', ]; } /** * 交叉校验:商品只能挂在末级分类 * (Laravel 12 FormRequest 的 after() 需返回单个 Closure,由容器 call 后注册到 Validator) */ public function after(): Closure { return function (Validator $validator): void { $data = (array) $validator->getData(); $categoryId = (int) ($data['category_id'] ?? 0); if ($categoryId > 0 && ProductCategoryModel::where('parent_id', $categoryId)->exists()) { $validator->errors()->add('category_id', '该分类下存在子分类,请选择末级分类'); } }; } public function messages(): array { return [ 'name.required' => '商品名称不能为空', 'name.max' => '商品名称最长 100 个字符', 'category_id.required' => '请选择商品分类', 'category_id.exists' => '商品分类不存在', 'supplier_id.exists' => '供应商不存在', 'status.in' => '状态值不正确', 'cost_price.numeric' => '成本价必须为数字', 'cost_price.min' => '成本价不能小于 0', ]; } }