laravel 如何验证数组索引和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50694208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel how to validate array index and values
提问by Joyal
I am submitting a single dimensional array of values to process on laravel 5.6
我正在提交一个单维值数组以在 laravel 5.6 上进行处理
quantity[4]:11
quantity[2]:14
I have to validate both the index and the value, index should exits as stocks,id and value must be integer and minimum 1
我必须同时验证指数和价值,指数应该作为股票退出,id 和价值必须是整数且最小值为 1
I tried
我试过
public function rules()
{
$rules = [
'quantity.*' => 'exists:stocks,id',
'quantity' => 'required|integer|min:1',
];
return $rules;
}
but its validating only the values not index, please share your thoughts and comments.
但它仅验证值而不是索引,请分享您的想法和评论。
回答by vietanhyt
I can not see anywhere we can validate array index with default Laravel validation. That why we need to write a custom one.
我看不到任何可以使用默认 Laravel 验证来验证数组索引的地方。这就是为什么我们需要编写一个自定义的。
public function rules()
{
$rules = [
'quantity.*' => 'required|integer|min:1',
'quantity' => [
'required',
'min:1', // make sure the input array is not empty <= edited
'array',
function($attribute, $value, $fail) {
// index arr
$ids = array_keys($value);
// query to check if array keys is not valid
$stockCntWithinArrIDs = StockModelFullNameWhaterver::whereIn('id', $ids)->count();
if ($stockCntWithinArrIDs != count($ids))
return $fail($attribute.' is invalid.'); // -> "quantity is invalid"
}
],
];
return $rules;
}
The main point is compare stock count result when query whereIn
(to reduce cost) their id with the array_keys of quantity
. Because quantity
's index is exists in stocks
, $stockCntWithinArrIDs
has to equal to count($ids)
, if not, there is at least one index is not as stocks
id.
重点是在查询whereIn
(以降低成本)他们的 id 与 array_keys时比较库存计数结果quantity
。因为quantity
的索引存在于 中stocks
,$stockCntWithinArrIDs
必须等于count($ids)
,如果不存在,则至少有一个索引不作为stocks
id。
You can use foreach ($ids)
then query the corresponding stock
to see if my solution work. But PLEASE DO NOTuse that solution on production env. :D
您可以使用foreach ($ids)
then 查询相应的stock
来查看我的解决方案是否有效。但请不要在生产环境中使用该解决方案。:D
Hope this help!
希望这有帮助!
Edited:
编辑:
See: https://laravel.com/docs/5.6/validation#custom-validation-rules
请参阅:https: //laravel.com/docs/5.6/validation#custom-validation-rules
回答by Anjo Tadena
Check this for array unique values https://laravel.com/docs/5.6/validation#rule-distinct
检查数组唯一值https://laravel.com/docs/5.6/validation#rule-distinct