Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JsonResponse in php

How to get id from here

JsonResponse {#457 ▼
  #data: "{"bill":{"id":11,"invoice_no":"9m36r9_1459170388239"}}"
  #callback: null
}

I am getting this output from this laravel code

return Response::json($response);

I tried json_decode but not worked here, a blank output is coming.

Thanks for any help.

like image 793
Drone Avatar asked Mar 29 '16 07:03

Drone


People also ask

How to fetch JSON object in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

How to get data from JSON array in PHP?

Use json_decode() Function to Extract Data From JSON in PHP. We will use the built-in function json_decode() to extract data from JSON. We will convert the JSON string to an object or an array to extract the data. The correct syntax to use this function is as follows.

How can access JSON decoded data in PHP?

As you're passing true as the second parameter to json_decode , in the above example you can retrieve data doing something similar to: $myArray = json_decode($data, true); echo $myArray[0]['id']; // Fetches the first ID echo $myArray[0]['c_name']; // Fetches the first c_name // ...


2 Answers

Try like this

$jsonResponse = Response::json([
        'id' => 1,
        'test' => 'test'
    ]);

$content = $jsonResponse->getContent();
$array = json_decode($content, true);
$id = $array['id']
like image 67
Viktor Kondolovskiy Avatar answered Oct 03 '22 21:10

Viktor Kondolovskiy


This works for me, using getData(). Laravel 5.7.

$jsonResponse = Response::json([
    'id' => 1,
    'test' => 'test'
]);
$content = $jsonResponse->getData();
$id = $content->id;
like image 45
Sem Avatar answered Oct 03 '22 20:10

Sem