Files
xin-procurement/app/Http/Requests/Product/ProductFormRequest.php
T
2026-08-27 14:20:09 +08:00

71 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Http\Requests\Product;
use App\Models\ProductCategoryModel;
use App\Models\SupplierModel;
use Closure;
use Illuminate\Validation\Rules\Exists;
use Illuminate\Validation\Validator;
use Modules\Common\Http\Requests\BaseFormRequest;
use Modules\SystemTool\Models\SysFileModel;
/**
* 商品档案 创建/编辑 验证(售价按客户等级上浮比例换算,不再维护等级价格行)
*/
class ProductFormRequest extends BaseFormRequest
{
protected $stopOnFirstFailure = true;
public function rules(): array
{
return [
'category_id' => ['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',
'price_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',
];
}
}