我正在通过ajax向控制器发送json数据,但最终我无法获得数据。
data that i send in playload
[{specification_id: "6", text_dec: "1", product_id: "21"},…]
0: {specification_id: "6", text_dec: "1", product_id: "21"}
1: {specification_id: "7", text_dec: "3", product_id: "21"}
2: {specification_id: "31", longtext_dec: "fsg", product_id: "21"}
controller
public function addnewcustomsubspecifications(Request $reqss)
{
// dd($reqss->json()->all());
// $this->validate($reqss, array(
// 'product_id' => 'required',
// 'specification_id' => 'required',
// 'text_dec' => 'nullable',
// 'longtext_dec' => 'nullable',
// ));
$datas = $reqss->json()->all();
foreach($datas as $data){
$add = CustomProductSpecification::create([
'product_id' => $data['product_id'],
'specification_id' => $data['specification_id'],
'text_dec' => $data['text_dec'],
'longtext_dec' => $data['longtext_dec'],
]);
$parent = Specification::where('id', '=', $data['specification_id'])->first();
}
return response()->json(array('data'=>$add,'parent'=>$parent));
}
如果我发表评论,我将得到:
"message": "Undefined index: longtext_dec",
"exception": "ErrorException",
如果没有,我得到:
{"message":"The given data was invalid.","errors":{"product_id":["The product id field is required."],"specification_id":["The specification id field is required."]}}
这是我的数据的样子:
array:3 [
0 => array:3 [
"specification_id" => "6"
"text_dec" => "1"
"product_id" => "21"
]
1 => array:3 [
"specification_id" => "7"
"text_dec" => "3"
"product_id" => "21"
]
2 => array:3 [
"specification_id" => "31"
"longtext_dec" => "fsggf"
"product_id" => "21"
]
注意:我认为验证问题是由于
$this->validate($reqss, array(
我需要使用类似$this->validate($reqss->json(), array(
,但是这不可能 方式
$reqss
应该更改为验证json代码(如上所述)longtext_dec
和text_dec
部分的if语句需要在未提供的情况下被忽略,并且不会返回第一个错误以上。附言:我的想法可能对您很愚蠢,但如果我知道真正的答案,我会 在这里问不对吗? :)
有什么主意吗?
答案 0 :(得分:2)
您可能必须分别评估每个数组。我想不出任何可以立即验证多行的东西。但是,由于text_dec和longtext_dec可以为空或丢失,因此在获取值时需要考虑到这一点:
$add = CustomProductSpecification::create([
'product_id' => $data['product_id'],
'specification_id' => $data['specification_id'],
'text_dec' => array_key_exists('text_dec', $data) ? $data['text_dec'] : null,
'longtext_dec' => array_key_exists('longtext_dec', $data) ? $data['longtext_dec'] : null,
]);
三元数将确保数组具有该列。如果是这样,它将添加该值;如果不是,则将传递一个空值。