php 如何在 Laravel 中验证数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42258185/
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
How to validate array in Laravel?
提问by Darama
I try to validate array POST in Laravel:
我尝试在 Laravel 中验证数组 POST:
$validator = Validator::make($request->all(), [
"name.*" => 'required|distinct|min:3',
"amount.*" => 'required|integer|min:1',
"description.*" => "required|string"
]);
I send empty POST and get this if ($validator->fails()) {}
as False
. It means that validation is true, but it is not.
我发送空 POST 并将其if ($validator->fails()) {}
作为False
. 这意味着验证是正确的,但事实并非如此。
How to validate array in Laravel? When I submit form with input name="name[]"
如何在 Laravel 中验证数组?当我提交表单时input name="name[]"
回答by Filip Sobol
Asterisk symbol (*) means that you want to check VALUES in the array, not the actual array.
星号 (*) 表示您要检查数组中的 VALUES,而不是实际数组。
$validator = Validator::make($request->all(), [
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
In the example above:
在上面的例子中:
- "Name" must be an array with at least 3 elements.
- Values in the "name" array must be distinct (unique) strings, at least 3 characters long.
- “名称”必须是至少包含 3 个元素的数组。
- “name”数组中的值必须是不同(唯一)的字符串,长度至少为 3 个字符。
EDIT:Since Laravel 5.5 you can call validate() method directly on Request object like so:
编辑:从 Laravel 5.5 开始,您可以直接在 Request 对象上调用 validate() 方法,如下所示:
$data = $request->validate([
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
回答by Nisal Gunawardana
I have this array as my request data from a HTML+Vue.js data grid/table:
我有这个数组作为来自 HTML+Vue.js 数据网格/表格的请求数据:
[0] => Array
(
[item_id] => 1
[item_no] => 3123
[size] => 3e
)
[1] => Array
(
[item_id] => 2
[item_no] => 7688
[size] => 5b
)
And use this to validate which works properly:
并使用它来验证哪些工作正常:
$this->validate($request, [
'*.item_id' => 'required|integer',
'*.item_no' => 'required|integer',
'*.size' => 'required|max:191',
]);
回答by sumit
The recommended way to write validation and authorization logic is to put that logic in separate request classes. This way your controller code will remain clean.
编写验证和授权逻辑的推荐方法是将该逻辑放在单独的请求类中。这样您的控制器代码将保持干净。
You can create a request class by executing php artisan make:request SomeRequest
.
您可以通过执行创建请求类php artisan make:request SomeRequest
。
In each request class's rules()
method define your validation rules:
在每个请求类的rules()
方法中定义您的验证规则:
//SomeRequest.php
public function rules()
{
return [
"name" => [
'required',
'array', // input must be an array
'min:3' // there must be three members in the array
],
"name.*" => [
'required',
'string', // input must be of type string
'distinct', // members of the array must be unique
'min:3' // each string must have min 3 chars
]
];
}
In your controller write your route function like this:
在您的控制器中编写您的路由功能,如下所示:
// SomeController.php
public function store(SomeRequest $request)
{
// Request is already validated before reaching this point.
// Your controller logic goes here.
}
public function update(SomeRequest $request)
{
// It isn't uncommon for the same validation to be required
// in multiple places in the same controller. A request class
// can be beneficial in this way.
}
Each request class comes with pre- and post-validation hooks/methods which can be customized based on business logic and special cases in order to modify the normal behavior of request class.
每个请求类都带有验证前和验证后的钩子/方法,可以根据业务逻辑和特殊情况自定义这些钩子/方法,以修改请求类的正常行为。
You may create parent request classes for similar types of requests (e.g. web
and api
) requests and then encapsulate some common request logic in these parent classes.
您可以为类似类型的请求(例如web
和api
)创建父请求类,然后在这些父类中封装一些常见的请求逻辑。
回答by Prafulla Kumar Sahu
Little bit more complex data, mix of @Laran's and @Nisal Gunawardana's answers
稍微复杂一点的数据,@Laran 和 @Nisal Gunawardana 的答案的混合
[
{
"foodItemsList":[
{
"id":7,
"price":240,
"quantity":1
},
{
"id":8,
"quantity":1
}],
"price":340,
"customer_id":1
},
{
"foodItemsList":[
{
"id":7,
"quantity":1
},
{
"id":8,
"quantity":1
}],
"customer_id":2
}
]
The validation rule will be
验证规则将是
return [
'*.customer_id' => 'required|numeric|exists:customers,id',
'*.foodItemsList.*.id' => 'required|exists:food_items,id',
'*.foodItemsList.*.quantity' => 'required|numeric',
];
回答by Chad Fisher
You have to loop over the input array and add rules for each input as described here: Loop Over Rules
您必须循环输入数组并为每个输入添加规则,如下所述:循环规则
Here is a some code for ya:
这是你的一些代码:
$input = Request::all();
$rules = [];
foreach($input['name'] as $key => $val)
{
$rules['name.'.$key] = 'required|distinct|min:3';
}
$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';
$validator = Validator::make($input, $rules);
//Now check validation:
if ($validator->fails())
{
/* do something */
}