我尝试在Laravel中验证数组POST:
$validator = Validator::make($request->all(), [
"name.*" => 'required|distinct|min:3',
"amount.*" => 'required|integer|min:1',
"description.*" => "required|string"
]);
我发送空POST并将此if ($validator->fails()) {}
作为False
。这意味着验证是正确的,但事实并非如此。
如何在Laravel中验证数组?当我使用input name="name[]"
答案 0 :(得分:146)
星号(*)表示您要检查数组中的VALUES,而不是实际的数组。
$validator = Validator::make($request->all(), [
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
在上面的示例中:
编辑:从Laravel 5.5开始,您可以直接在Request对象上调用validate()方法,如下所示:
$data = $request->validate([
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
答案 1 :(得分:14)
我将此数组作为来自HTML + Vue.js数据网格/表的请求数据:
[0] => Array
(
[item_id] => 1
[item_no] => 3123
[size] => 3e
)
[1] => Array
(
[item_id] => 2
[item_no] => 7688
[size] => 5b
)
并使用它来验证哪些工作正常:
$this->validate($request, [
'*.item_id' => 'required|integer',
'*.item_no' => 'required|integer',
'*.size' => 'required|max:191',
]);
答案 2 :(得分:5)
推荐的编写验证和授权逻辑的方法是将该逻辑放在单独的请求类中。这样,您的控制器代码将保持干净。
您可以通过执行php artisan make:request SomeRequest
在Request类的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
]
];
}
在控制器中这样编写路由功能
public function someFunction(SomeRequest $request)
{
//request is already validated before reaching this point
//your controller logic goes here
}
请求类带有验证前后的钩子/方法,可以根据业务逻辑和特殊情况自定义钩子/方法,以修改请求类的正常行为。
您可以为类似类型的请求(例如Web和api请求)创建父请求类,然后在这些父类中封装一些常见的请求逻辑。
答案 3 :(得分:3)
更复杂的数据,包括@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
}
]
验证规则为
return [
'*.student_id' => 'required|numeric|exists:customers,id',
'*.foodItemsList.*.id' => 'required|exists:food_items,id',
'*.foodItemsList.*.quantity' => 'required|numeric',
];
答案 4 :(得分:1)
您必须循环输入数组并为每个输入添加规则,如下所述:Loop Over Rules
以下是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 */
}
答案 5 :(得分:0)
下面的代码对我来说是来自ajax调用的数组。
$form = $request->input('form');
$rules = array(
'facebook_account' => 'url',
'youtube_account' => 'url',
'twitter_account' => 'url',
'instagram_account' => 'url',
'snapchat_account' => 'url',
'website' => 'url',
);
$validation = Validator::make($form, $rules);
if ($validation->fails()) {
return Response::make(['error' => $validation->errors()], 400);
}