我很难解码laravel中的json输入。。我正在构建一个Restful API,当我使用RestClient发送帖子数据,然后在laravel中死亡并转储时,我得到了
object(Symfony'Component'HttpFoundation'ParameterBag)#205 (1) {
["parameters":protected]=>
array(6) {
["firstName"]=>
string(8) "John"
["lastName"]=>
string(7) "Doe"
["bloodGroup"]=>
string(2) "B+"
["phone"]=>
string(8) "+9999999"
["address"]=>
string(8) "Somecity"
["symptoms"]=>
string(3) "Bla"
}
}
现在我已经绑定使用访问数据
$data = Input::json();
echo $data->firstName;
那不起作用。。尝试将其转换为数组,然后访问像CCD_ 1一样不起作用。
array(1) {
["*parameters"] =>
array(6) {
["firstName"]=>
string(8) "John"
["lastName"]=>
string(7) "Doe"
["bloodGroup"]=>
string(2) "B+"
["phone"]=>
string(8) "+9999999"
["address"]=>
string(8) "Somecity"
["symptoms"]=>
string(3) "Bla"
}
}
我想解码数据,然后将其保存到数据库,这里有一个构建类似应用程序的教程。。
我尝试过这里解释的post_index()方法,但没有成功。
http://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/
您可以使用->get()
从Symfony'Component'HttpFoundation'ParameterBag
响应访问属性。
$input = Input::json();
$input->get('firstName')
您还可以将所有输入获取为一个数组,然后使用(object)
将其类型转换为一个对象。请注意,如果您的属性不存在,这将引发一个错误,因此如果我将您放在哪里,我将使用上面提到的->get()
方法。
$input = (object)Input::all();
$input->firstName;
基于我的实验
如果您使用JSON 从Javascript发送多个对象的数组(如以下示例)
[{crop_id: 1, test_id: 6},{crop_id: 1, test_id: 7},{crop_id: 1, test_id: 8}]
您需要在PHP中使用Input::json()->all()函数。
$arr = Input::json()->all();
$crop_id = $arr[0]['crop_id'];
$test_id = $arr[0]['test_id'];