I am working on a laravel project where I need to show a list and stats from API. For stats and a list of content, there are separate URLs. And I have to display both on one page.
How to call multiple API URLs on a page? Suppose https://localhost/api/games and https://localhost/api/stats are two URLs.
I am using Laravel version 7 PHP version 7.2.3
Controller here:
public function index()
{
$collection = Http::withHeaders([
'x-api-host' => $host,
'x-api-key' => $key
])->get('https://localhost/api/games');
return view('welcome', ['collection'=>$collection]);
}
CodePudding user response:
As esel said Just do that a second time :
public function index()
{
$collection = Http::withHeaders([
'x-api-host' => $host,
'x-api-key' => $key
])->get('https://localhost/api/games');
$collection2 = Http::withHeaders([
'x-api-host' => $host,
'x-api-key' => $key
])->get('https://localhost/api/stats');
return view('welcome', ['collection'=>$collection,'collection2'=>$collection2]);
}
CodePudding user response:
Synchronous call
you can call the second api after the first
public function index()
{
$collection = Http::withHeaders([
'x-api-host' => $host,
'x-api-key' => $key
])->get('https://localhost/api/games');
$stats = Http::withHeaders([
'x-api-host' => $host,
'x-api-key' => $key
])->get('https://localhost/api/stats');
return view('welcome', ['collection'=>$collection, 'stats'=>$stats]);
}
in this situation the second http request will be send after your first request has been resolved to a response
Asynchronous call
since maybe you are looking for asynchronous call ( sending http request calls after each other - before the first one response.
Laravel is not a good choice for doing this. however you can achieve this with below scenario:
- install a websocket provider package (like socket.io)
- define Queable jobs for each request (
gamesCallJob
&statCallJob
) - create events for each resolution (
gameCallREsolveEvent
&statCallREsolveEvent
) - omit the events in the handle method of each jobs.
- define a listener for each listeners: in the listener you can check if all events has been settled (you can use a cache server or DB table for holding the resolved event) then send data to user
- in the controller just dispatch the jobs to the queues then start the websocket channel
As you may have notice, the Laravel is not a good choice for calling these calls Asynchronously