-
You need to return
$response['data']instead of the whole assoc array. -
I would recommend the use of
GuzzleHttpinstead of plaincurl: http://docs.guzzlephp.org/en/stable/ If the HTTP endpoint is often going to be hit, I'd consider abstracting it away into a separateApiClientwhich you initialize only once and then call methods from it to fetch data.
If you are into tests, you can resolve the client via the IoC container to swap it with a fake implementation during your tests because network requests are generally too slow for non-integration tests.
An example (might not work):
class ApiClient
{
private $http;
public function __construct(?string $token, $baseURL = null)
{
if ($token = null) {
throw new \Exception();
}
$options = ['headers' => ['Authorization' => 'Bearer ' . $token]];
if (isset($baseURL)) {
$options['base_uri'] = $baseURL;
}
$this->http = new \GuzzleHttp\Client($options);
}
public function fetchConsumers(array $query): array
{
try {
$res = $this
->http
->get($this->getUrl('consumers/get'), compact('query'));
} catch (Exception $ex) {
\Log::error($ex);
return [];
}
return $this->asArray($res);
}
private function getUrl(string $endpoint): string
{
return $this->http->getConfig('base_uri') . '/' . $endpoint;
}
private function asArray(ResponseInterface $res)
{
return json_decode($res->getBody()->getContents(), true);
}
}
Register the client as a singleton in AppServiceProvider, e.g.
$this->app->singleton(ClientContract::class, static function () {
return new ApiClient(config('external_api.token'), config('external_api.base_uri'));
});
Just to give you an idea of how the problem can be tackled, do not take it as an absolute thing.