Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle nested JSON object request in Laravel 5?

We had this webservice running in Laravel 5 and AngularJs/Ionic for handling the web. When we post request from the web (client) to webservice (backend), we passed nested JSON object. We are having an issue to read all child objects under parent object in the server side.

{
    "name": "test",
    "description": "test",
    "startdate": "2016-02-21T13:00:00.000Z",
    "enddate": "2016-02-23T13:00:00.000Z",
    "coach": {
        "uuid": "76fdd664-d830-11e5-9d46-00ffc9587cbc"
    },
    "category": {
        "uuid": "771e6de4-d830-11e5-9d46-00ffc9587cbc"
    },
    "useruuid": "76d65a2d-d830-11e5-9d46-00ffc9587cbc",
    "routines": ["775b2726-d830-11e5-9d46-00ffc9587cbc"]
}

This JSON has been verified ok and I also we managed to get the basic one such as name, endate etc etc BUT not the nested object one.

We are using something like this in Laravel 5:

$incomingdata = $request->json()->all();
$name = $incomingdata->name; // works
$startdate = $incomingdata->startdate; // works
$coach_uuid = $incomingdata->coach()->uuid; // didn't work !!!

How do I achieve this?

like image 320
dcpartners Avatar asked Feb 22 '16 07:02

dcpartners


1 Answers

I don't know about Laravel 5.0, but in Laravel 5.6 I had to do something quite different. None of the code in other answers worked for me.

Here is what I found to work correctly:

$name = $request->input('name');
$startdate = $request->input('startdate');
$coach_uuid = $request->input('coach.uuid');
print_r($name.'<br />');
print_r($startdate.'<br />');
print_r($coach_uuid.'<br />');

The above prints:

test
2016-02-21T13:00:00.000Z
76fdd664-d830-11e5-9d46-00ffc9587cbc

Reference: https://laravel.com/docs/5.6/requests#retrieving-input

like image 171
Schparky Avatar answered Oct 02 '22 20:10

Schparky