“ message”:“非法字符串偏移量'product_id'”,在Laravel RESTfull API中

时间:2020-10-11 13:55:00

标签: json laravel

Am正在开发Laravel RESTful API,使用php关联数组将Json对象的数组保存到DB中,这是错误的体现。

"message": "Illegal string offset 'product_id'",
"exception": "ErrorException",
...

这是要保存在Mysql DB中的JSON对象数组

 "userId": "1",
 "userName": "Dan",
 "userEmail": "dan@gmail.com"
 "product": [
     {
         "product_id": "31",
         "product_name": "Orange",
         "product_price": "USD 0.5"
      }
    ]
}

这是用于将Json对象保存到数据库中的php函数。

$userId = $request -> input('userId');
$userName = $request ->input('userName');
$userEmail = $request ->input('userEmail');
$data = array(
    "userId"=>$userId,
    "userName"=>$userName,
    "userEmail"=>$userEmail
);

$user = User::create($data); 
if($order){
    //Storing the received JSON in $json.
    $json = file_get_contents('php://input');

    // Decode the received JSON and store into $obj
    $obj = json_decode($json,true);
    foreach($obj as $product){
        $product_id = $product['product_id'];
        $product_name = $product['product_name'];
        $product_price = $product['product_price'];
        $product = array(
            "product_id" => $product_id,
            "product_name" => $product_name,
            "product_price" => $product_price
        );
        DB::table('products')->insert($product); 
    }

    if($product){
        // On query success it will print below message.
        $MSG = 'Data Successfully Submitted.' ;

       // Converting the message into JSON format.
       $json = json_encode($MSG);

       // Echo the message.
       echo $json ;
    }
    else{
        echo 'Try Again';
    }

我在哪里弄错。预先谢谢你!

0 个答案:

没有答案