Laravel 对象数组验证
Laravel array of objects validation
我正在尝试在 Laravel 中对对象的关联数组进行验证。
我传递给控制器的有效 JSON 字符串如下所示:
{
'create': [
{
'artnr': '123456',
'unit': 'Stk.'
},
{
'artnr': '23456',
'unit': 'Kg.'
}
],
'update': [
{
'id': 1
'artnr': '567890',
'unit': 'Stk.'
},
{
'id': 2
'artnr': '67836',
'unit': 'Kg.'
}
]
}
验证数据的控制器函数如下所示:
public function store(Request $request)
{
$request->replace(array(
'create' => json_decode($request->create),
'update' => json_decode($request->update)
));
$validator = Validator::make($request->all(), [
'create' => 'required|array',
'create.*.artnr' => 'required|max:20',
'create.*.unit' => 'max:20',
'update' => 'required|array',
'update.*.id' => 'required|exists:products,id',
'update.*.artnr' => 'required|max:20',
'update.*.unit' => 'max:20'
])->validate();
}
虽然我在 store
函数中指定每个对象都必须存在 artnr
,但当我传递一个没有 artnr
的对象时,控制器不会抛出错误。
知道我做错了什么吗?
编辑
好的,在遵循 user2486 的建议并使用不同的示例数据后,我现在发现当我将 id
、artnr
、unit
等属性作为关联数组。像这样:
$arr = array(
'create' => array(
array(
'artnr' => '123456',
'unit' => 'Kg'
), array(
'unit' => 'Stk.'
)
), 'update' => array(
array(
'id' => 1,
'unit' => 'Stk.'
), array(
'id' => 2,
'artnr' => '123456',
'unit' => 'Kg'
)
)
);
然而,当我解码我的 JSON 字符串时,属性被解析为一个 对象 ,因此不会抛出任何错误!
验证器规则是否可能对对象使用不同类型的符号?
如果不能验证对象,我想我会把每个对象都转换成一个关联数组。
好的,所以解决方案是像这样调用我的 json_decode
函数
json_decode($request->create, true)
。
将第二个参数设置为 true
时,该函数将每个 JSON 对象转换为关联数组。
我正在尝试在 Laravel 中对对象的关联数组进行验证。
我传递给控制器的有效 JSON 字符串如下所示:
{
'create': [
{
'artnr': '123456',
'unit': 'Stk.'
},
{
'artnr': '23456',
'unit': 'Kg.'
}
],
'update': [
{
'id': 1
'artnr': '567890',
'unit': 'Stk.'
},
{
'id': 2
'artnr': '67836',
'unit': 'Kg.'
}
]
}
验证数据的控制器函数如下所示:
public function store(Request $request)
{
$request->replace(array(
'create' => json_decode($request->create),
'update' => json_decode($request->update)
));
$validator = Validator::make($request->all(), [
'create' => 'required|array',
'create.*.artnr' => 'required|max:20',
'create.*.unit' => 'max:20',
'update' => 'required|array',
'update.*.id' => 'required|exists:products,id',
'update.*.artnr' => 'required|max:20',
'update.*.unit' => 'max:20'
])->validate();
}
虽然我在 store
函数中指定每个对象都必须存在 artnr
,但当我传递一个没有 artnr
的对象时,控制器不会抛出错误。
知道我做错了什么吗?
编辑
好的,在遵循 user2486 的建议并使用不同的示例数据后,我现在发现当我将 id
、artnr
、unit
等属性作为关联数组。像这样:
$arr = array(
'create' => array(
array(
'artnr' => '123456',
'unit' => 'Kg'
), array(
'unit' => 'Stk.'
)
), 'update' => array(
array(
'id' => 1,
'unit' => 'Stk.'
), array(
'id' => 2,
'artnr' => '123456',
'unit' => 'Kg'
)
)
);
然而,当我解码我的 JSON 字符串时,属性被解析为一个 对象 ,因此不会抛出任何错误!
验证器规则是否可能对对象使用不同类型的符号?
如果不能验证对象,我想我会把每个对象都转换成一个关联数组。
好的,所以解决方案是像这样调用我的 json_decode
函数
json_decode($request->create, true)
。
将第二个参数设置为 true
时,该函数将每个 JSON 对象转换为关联数组。