skip to Main Content

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]);
    }

2

Answers


  1. 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:

    1. install a websocket provider package (like socket.io)
    2. define Queable jobs for each request (gamesCallJob & statCallJob)
    3. create events for each resolution (gameCallREsolveEvent & statCallREsolveEvent)
    4. omit the events in the handle method of each jobs.
    5. 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
    6. 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

    Login or Signup to reply.
  2. 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]);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search