首页 > 解决方案 > “消息”:“非法字符串偏移 'product_id'”,在 Laravel RESTfull API 中

问题描述

我正在开发 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 对象保存到 DB 中的 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';
    }

伙计们,我在哪里犯错。先感谢您!

标签: jsonlaravel

解决方案


推荐阅读