-1

How to create a nested json response in Laravel 5? For example:

"response":["status":"OK",
            "data":{ "user":{"name": "Shriyansh",
                             "email":"[email protected]",
                             "contact":"1234567890",
                             "fcmToken":"Token@123"
                            },
                     "event":{"status":"successful",
                              "status_code":4
                             }
                   }
           ]
2
  • 1
    return response()->json([ 'status' => 'OK', 'data' => $data ]); here $data is array Commented Aug 25, 2017 at 12:39
  • you can use $data as multidimensional array for desire result Commented Aug 25, 2017 at 12:43

3 Answers 3

4

Create an array to hold your response like this:

$data = [
            "status"=> "OK",
            "data"=> [ 
                        "user" => [
                                   "name"=> "Shriyansh",
                                   "email"=>"[email protected]",
                                   "contact"=>"1234567890",
                                   "fcmToken"=>"Token@123"
                        ],
                        "event"=> [
                                   "status" => "successful",
                                   "status_code" => 4
                         ]
               ]
       ]

Then return your data using Laravel response method like this:

return response()->json($data, 200);

So Laravel will convert your array into json format and send it back to your client.

Sign up to request clarification or add additional context in comments.

Comments

1

You should try this:

$json = json_encode(array(
    "status"=>"OK",
    "user" => array(
      "name"=> "Shriyansh",
      "email"=>"[email protected]",
      "contact"=>"1234567890",
      "fcmToken"=>"Token@123"
    ),
    "event" => array(
      "status" => "successful",
      "status_code" => 4
    )
));

Comments

0

You can use JSON Response to return the JSON in Laravel. Example: Assuming you have the required data in the $data variable,

return response()->json([
    'data' => $data
],200);

where, 200 is status code. status will be added as per the status code by laravel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.