Andres
Andres

Reputation: 43

Handling guzzle 6 response body in laravel

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

Upvotes: 2

Views: 2865

Answers (1)

rap-2-h
rap-2-h

Reputation: 31948

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

Upvotes: 2

Related Questions