我只想确保我的数据来自JS端,是一个数组。因此,从接受的答案可以看出,在验证中写'array'
就足够了。但就我而言,当我写:
$request->validate([
'tags' => 'array',
]);
并使用Postman传递数组[1,2,3]
,我得到一个错误["The tags must be an array."]
,php将其处理为字符串,因此当我尝试获取例如第一个元素$request->tags[0]
时,我会收到'['
。这是怎么回事?
当你传递[1,2,3]
时,它似乎不是一个数组,它实际上只是一个字符串。 当你在PHP中把一个字符串当作一个数组时,它会给你那个字符,所以$request->tags[0]
只是给你字符串中的第一个字符,即[
。
使用邮递员并添加键值对时,请像这样设置键和值...
+--------+-------+
| Key | Value |
+--------+-------+
| tags[] | 1 |
| tags[] | 2 |
| tags[] | 3 |
+--------+-------+
<form ..>
<input name="tags[]" value="1">
<input name="tags[]" value="2">
<input name="tags[]" value="2">
</form>
<script>
//your code to serialise and post form through JS goes here
</script>
在您的请求类中
//TagsRequest.php
public function rules(){
return [
'tags'=>['array'],
'tags.*'=>[
//add rules for tags array elements
]
]
}