Reputation: 1333
In my Laravel-8 application, I have this api as json:
api/tracking/{TrackerID}?sub-key=jkkmkf
which looks like:
api/tracking/19SB22?sub-key=jkkmkf
It is a GET request
When I tried to consume it as shown below, I got this error:
ErrorException Undefined offset: 0
and it points to this line:
$current = $json[0];
How do I resolve this?
Thanks
public function index() {
$request = Request::create('/api/tracking', 'GET');
$response = Route::dispatch($request);
$information = $response->content();
$json = json_decode($information, true);
$current = $json[0];
$geo = explode(',', $json[0]['current_asset_position_coord']);
return view('welcome', [
'current' => $current,
'json' => $json,
'geo' => $geo
]);
}
Upvotes: 0
Views: 336
Reputation: 587
It means that the array ($json
) doensn't contains value with 0 key, your json_decode
returns you an empty array.
To make requests to external API's please have a look at Guzzle
use GuzzleHttp\Client;
$client = new Client();
$res = $client->get('https://example.com/api/tracking/19SB22', ['sub-key' => 'jkkmkf']);
echo $res->getStatusCode(); // 200
$json = $res->getBody()->getContents();
Upvotes: 1