Ashik Basheer
Ashik Basheer

Reputation: 1601

Laravel 5 - Returned json is a simple string

Scenario: REST api where a client requests data from server via GET method

I am returning an array from HomeController (Server side: Laravel 5)

return ['Status' => 'Success', 'SearchResponse' => $apiresponse, 'AuthToken' => $property];

The above response is generated from a URL http://example.com/flightSearch

On the client side (Laravel 4)

        $input=Input::all();
        $url = 'http://example.com/flightSearch';
        $data = array(
             'client_id' => 'XXX',
             'api_secret' => 'YYY',
             'method'=>'SearchFlight',
             'adult'=>$input['adult'],
             'children'=>$input['children'],
             'infant'=>$input['infant'],
             'departCity'=>$input['departCity'],
             'arrivalCity'=>$input['arrivalCity'],
             'departDate'=>$input['departDate'],
             'returnDate'=>$input['returnDate'],
             'journeyType'=>$input['journeyType']
             );

        $params = http_build_query($data);
        $result = file_get_contents($url.'?'.$params);

        $response = json_decode($result);
        return $response->Status //Works
        return $response->AuthToken //Works
        return $response->SearchResponse //Throws following Error

Error:

The Response content must be a string or object implementing __toString()

Solution:

The variable $apiresponse was an object returned from a remote server. Adding the variable to an object solved the problem

return ['Status' => 'Success', 'SearchResponse' => array($apiresponse), 'AuthToken' => $property];

Upvotes: 1

Views: 24176

Answers (2)

SirajuddinLuck
SirajuddinLuck

Reputation: 141

$test1 = array('name'=>'gggg');
print_r($test1); //answer: Array ([name]=>gggg)
$test2 = json_encode($test1);
print_r($test2); //answer: {"name":"gggg"}
$test3 = json_decode($test2);
echo $test3->name; //answer:  gggg

Upvotes: 0

lukasgeiter
lukasgeiter

Reputation: 152860

Update

Since you have a JSON string you can simply use json_decode():

$response = json_decode($result);
return $response->Status;

The Response content must be a string or object implementing __toString()

This is just because you're returning the $response->SearchResponse from your controller action. Using it like $response->SearchResponse->SomeProperty will just work fine. No need for array($apiresponse) If you want to see all the contents of that variable use var_dump():

var_dump($response->SearchResponse);

Assuming you created the $response with Laravels help this should be an instance of Illuminate\Http\JsonResponse.

You can get the data (already decoded) with getData():

$data = $response->getData();
echo $data->Name

Upvotes: 3

Related Questions