0

While trying to request data from en external API, I want to control how the response is being passed to my view or database. However what would be the correct way to write the code below, so instead of simply echoing the data onto the view I would like to store it inside an object that I can pass to my view or model in a more controlled way?

public function index()
    {
        $contents = $this->saveApiData();
        return View::make('stats.index')->with('contents', $contents);
    }

     public function saveApiData()
    {
        $client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
        $res = $client->request('GET', "data" . "/blob");
        echo $res->getStatusCode();
        echo $res->getBody();
    }
dwigt
  • 611
  • 1
  • 8
  • 18
  • Maybe [this](https://stackoverflow.com/a/44284841/6193316) (please read the comments too) will help you. I don't know another way until yet – UfguFugullu Jun 01 '17 at 11:56

1 Answers1

1

Just put them together in an array and return it. You never echo data in a function to return them.

public function saveApiData()
{
    $client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
    $res = $client->request('GET', "data" . "/blob");

    $contents = [
        'status' => $res->getStatusCode(),
        'body' => $res->getBody()
    ];

    return $contents;
}
Sandeesh
  • 11,486
  • 3
  • 31
  • 42
  • Thank you, however, this seems to return the response body as a plain string. Do you know of a way I can control the JSON response similar to if it was a JavaScript object? – dwigt Jun 01 '17 at 13:01
  • 1
    Use `json_decode` to convert the string to an array. – Sandeesh Jun 01 '17 at 13:05