2

I'm making a Laravel 5.2 project which is communicating with a local API. And I'm having issues handling the Guzzle response body.

My controller:

public function getClients(){
    $guzzle = new Client();
    try{

        $response = $guzzle->request('GET', 'http://localhost:3000/client')->getBody();           
        return view('home.clients', ['clients' => $response]);

    }catch(ClientException $e){
     //Handling the exception
    }
}

My blade View:

<h2>Client list</h2>

{{ $clients }}//Just to inspect it

@forelse ($clients as $client)
    <h3>{{ $client->name }}</h3>
    <h3>{{ $client->email }}</h3>
    <h3>{{ $client->country }}</h3>
@empty
    <h3>No clients here</h3>
@endforelse

No errors on the loop or the controller, also is showing the Stream Object in the browser but in the loop doesn't display anything.

I've already read the Guzzle 6 response body documentation, but it's not that clear for a newbie in this like me.

Thoughts?

Browser output: browser output

Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
Andres
  • 43
  • 1
  • 3

1 Answers1

2

You have to decode this JSON with json_decode():

public function getClients(){
    $guzzle = new Client();
    try {

        $response = json_decode($guzzle->request('GET', 'http://localhost:3000/client')->getBody());           
        return view('home.clients', ['clients' => $response]);

    } catch(ClientException $e){
         //Handling the exception
    }
}

And you can remove {{ $clients }}//Just to inspect it from your view.

More info about JSON and Guzzle here: Guzzle 6: no more json() method for responses

Community
  • 1
  • 1
rap-2-h
  • 30,204
  • 37
  • 167
  • 263