I have a problem when retrieve the returned data from another application using GuzzleClient.
For example, in the First Application, I call to Second application test
function to get the returned data as Collective data type, however I have not idea how to do that. I try to json_decode the response in call_another_server
function but it will become array, if i not using json_decode, it will just return as a string.
First Application
public function call_another_server()
{
$client = new GuzzleClient();
$url = 'http://127.0.0.1:1111/testing'; ##### This url will call to second application@test() function
$response = $client->request('GET', $url);
$data = json_decode($response->getBody()->getContents(), true);//retrieve the response data and decode it as array
dd($response);
}
Second Application
public function test()
{
$array = ["1" => "one", "2" => "two"];
return (collect($array)); ##### return as collective
}
Returned Result (in call_another_server
, dd($response) )
Expected Result ( returned as Collection )
Can anyone can guide me how to return as my expected result in call_another_server
function? I know I can manipulate the response in call_another_server
using collect helper to make the response become Collection type. But I hope I can just retrieve the original data type from test
function.
Any guidance and suggestion is appreciated. Thanks!
You can not retrieve the Collection you want that way. Because when you return (collect($array))
your app is casting your Collection to array, and then convert it to json (for json response).
To avoid casting to array you can serialize your Collection, and then send the serialized data (being string now) as response.
So :
1. First Application
public function call_another_server()
{
[...]
$data = unserialize($response->getBody()->getContents());//unserialize retrieved data
dd($data);
}
2. Second Application
public function test()
{
[...]
return serialize(__YOUR_COLLECTION_HERE__); // return serialized collection
}
BUT WARNING :
... Do not pass untrusted user input to unserialize() ...
Illuminate\Support\Collection
). Also valid for any object class contained in the collection data eventually.