You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel7 控制器单个action中如何发起多个API接口调用

解决方案

方案1:串行请求(实现最简单,适合请求量小的场景)

注意原代码直接将HTTP响应实例传给视图是错误的,必须调用json()/collect()方法解析响应体才能拿到接口返回的实际数据。你可以直接新增第二个接口的请求逻辑,将两类数据一同传给视图:

public function index()
{
    // 复用公共请求头
    $commonHeaders = [
        'x-api-host' => $host,
        'x-api-key' => $key
    ];
    
    // 获取游戏列表数据,需要集合格式可替换为->collect()
    $games = Http::withHeaders($commonHeaders)
        ->get('https://localhost/api/games')
        ->json();
    
    // 获取统计数据
    $stats = Http::withHeaders($commonHeaders)
        ->get('https://localhost/api/stats')
        ->json();
    
    // 两个参数一同传给视图
    return view('welcome', compact('games', 'stats'));
}

方案2:并发请求(性能更优,适合对接口响应速度有要求的场景)

两个接口相互独立,可通过Laravel HTTP客户端的请求池实现并发调用,总耗时将从两个接口的耗时之和降低为耗时更长的单个接口的耗时:

use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;

public function index()
{
    $commonHeaders = [
        'x-api-host' => $host,
        'x-api-key' => $key
    ];
    
    // 并发发送两个请求
    $responses = Http::pool(function (Pool $pool) use ($commonHeaders) {
        return [
            $pool->withHeaders($commonHeaders)->get('https://localhost/api/games'),
            $pool->withHeaders($commonHeaders)->get('https://localhost/api/stats'),
        ];
    });
    
    // 按请求顺序提取解析后的数据
    $games = $responses[0]->json();
    $stats = $responses[1]->json();
    
    return view('welcome', compact('games', 'stats'));
}

视图层调用示例

在welcome.blade.php中可以分别渲染两类数据:

{{-- 统计数据展示 --}}
<div class="stats-panel">
    <span>总游戏量:{{ $stats['total_count'] ?? 0 }}</span>
    <span>本周新增:{{ $stats['weekly_add'] ?? 0 }}</span>
</div>

{{-- 游戏列表展示 --}}
<ul class="games-list">
    @foreach($games as $game)
        <li>{{ $game['title'] }} - {{ $game['publish_time'] }}</li>
    @endforeach
</ul>

内容的提问来源于stack exchange,提问作者webfuelcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:45:07