5

I am having a hard time decoding json input in laravel .. am building a Restful API and when i send post data using RestClient and then die and dump in laravel i got

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" } } 

Now i have tied to access the data using

$data = Input::json(); echo $data->firstName; 

that does not work .. tried to convert it to array and then access like $data['firstName'] does not work .

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" } } 

i want to decode the data then save it to db, Here is a tutorial building similar App ..

I have tried the post_index() method explained here but no luck .

http://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/

2
  • As you can see firstName is inside of the *parameters array, hence can be accessed by $data['*parameters']['firstName'], however there's probably a reason that they're protected. Commented Apr 27, 2014 at 18:21
  • tried that too but no luck Commented Apr 27, 2014 at 18:26

2 Answers 2

9

You can use ->get() to access properties from a Symfony\Component\HttpFoundation\ParameterBag response.

$input = Input::json(); $input->get('firstName') 

You can also get all inputs as an array and then type cast it to an object with (object). Note that this will throw an error if your property doesn't exists, so if I where you, I would use the ->get() method mentioned above.

$input = (object)Input::all(); $input->firstName; 
Sign up to request clarification or add additional context in comments.

5 Comments

that gives object(stdClass)#205 (0) {}
@user2202757, that means that your object is empty.
Well Input::all() returns an empty array
i used var_dump to see all the input data grabbed by Input::all() then it returns an empty array and error but if i use dd() then i can see the data .Strange problem .. But Thank you Input::all() works fine ....
@user2202757 you must set your request 'Content-Type' header to 'application/json' to see those inputs in Input::all() collection.
2

Based on my experiment

If you are sending an array of multiple objects like the following example from the Javascript using JSON

[{crop_id: 1, test_id: 6},{crop_id: 1, test_id: 7},{crop_id: 1, test_id: 8}] 

You need to use Input::json()->all() function in PHP.

$arr = Input::json()->all(); $crop_id = $arr[0]['crop_id']; $test_id = $arr[0]['test_id']; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.