嗨,我正在尝试实现一个用于下订单的API。我想使用laarvel验证来验证数据。以下是我想要验证的示例输入值
{
"phone": "phone",
"cart_items": [
{
"category_id": "1",
"product_id": "1",
"product_count": "1",
"quantity": "1",
"prize_per_unit": "1"
},
{
"category_id": "2",
"product_id": "1",
"product_count": "1",
"quantity": "1",
"prize_per_unit": "1"
}
],
"total": "2",
"net_amount": "100"
}
我要根据产品ID和类别ID根据产品表验证产品ID。产品表包含product_id和类别ID, 以下是我的验证规则。
$validator=Validator::make($request->all(),[
//'customer_id'=>['required','exists:users,id'],
'phone'=>['required','max:12',function($attribute, $value, $fail) {
$re = '/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[6789]\d{9}$/';
if (preg_match_all($re, $value, $matches)) {
return true;
}
return $fail($attribute.' is invalid.');
} ],
'cart_items.*.category_id'=>['required','exists:categories,cat_id'],
'cart_items.*.product_id'=>['required',Rule::exists('products','product_id')->where(function($query)use ($request) {
$query->where('category_cat_id',$request->category_id);
})],
'cart_items.*.product_count'=>['required','integer','max:100','min:1',''],
'cart_items.*.quantity'=>['required','integer'],
'cart_items.*.delivery_charge'=>['nullable','integer','min:0'],
'cart_items.*.prize_per_unit'=>['required','integer','min:1'],
'total'=>['required','integer','min:1'],
'net_amount'=>['required','integer','min:1'],
],[
'category_id.exists'=>'Not a valid category',
'product_id.exists'=>'Not a valid product'
]);
我的问题是如何验证此规则
'cart_items.*.product_id'=>['required',Rule::exists('products','product_id')->where(function($query)use ($request)
{
$query->where('category_cat_id',$request->category_id);
})],
将替换为数组的$request->category_id