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

Laravel 8 Blade视图展示IMDB API数据失败求助

问题:Laravel 8中调用IMDB API后无法在Blade视图正确展示数据

背景

调用IMDB API获取数据后,在Blade视图展示时频繁出错,核心原因是对API返回的响应结构理解有误。

API示例响应

{
  "d": [
    {
      "i": {
        "height": 1500,
        "imageUrl": "https://m.media-amazon.com/images/M/MV5BYTRiNDQwYzAtMzVlZS00NTI5LWJjYjUtMzkwNTUzMWMxZTllXkEyXkFqcGdeQXVyNDIzMzcwNjc@._V1_.jpg",
        "width": 1102
      },
      "id": "tt0944947",
      "l": "Game of Thrones",
      "q": "TV series",
      "rank": 36,
      "s": "Emilia Clarke, Peter Dinklage",
      "v": [
        {
          "i": {
            "height": 720,
            "imageUrl": "https://m.media-amazon.com/images/M/MV5BZTg4YzdjNTctNDg5Mi00ZmU1LTkzOWEtNmMyNDBjZjNhNTJiXkEyXkFqcGdeQXRyYW5zY29kZS13b3JrZmxvdw@@._V1_.jpg",
            "width": 1280
          },
          "id": "vi59490329",
          "l": "Official Series Trailer",
          "s": "3:19"
        },
        {
          "i": {
            "height": 1080,
            "imageUrl": "https://m.media-amazon.com/images/M/MV5BMTljMTZmNDUtNTEzNy00NDgyLTk2N2QtOTI3MGQyNWE0MTI5XkEyXkFqcGdeQWplZmZscA@@._V1_.jpg",
            "width": 1920
          },
          "id": "vi1097842713",
          "l": "The 8 Most Surprising Moments From \"Game of Thrones\" to Rewatch",
          "s": "3:39"
        },
        {
          "i": {
            "height": 720,
            "imageUrl": "https://m.media-amazon.com/images/M/MV5BMTg0ODM4NTc3OV5BMl5BanBnXkFtZTgwODAwODE1OTE@._V1_.jpg",
            "width": 1280
          }
        }
      ]
    }
  ],
  "q": "game of thr",
  "v": 1
}

当前代码问题

控制器代码

public function api(Request $request)
{
    $userInput = $request->input();

    $response = Http::withHeaders(
        [
            "x-rapidapi-host"=> "xxxxxxxxx",
            "x-rapidapi-key"=> "xxxxxxxxxxx",
        ]
    )->get("https://imdb8.p.rapidapi.com/auto-complete?q=",$userInput)->json();

    return json_encode(array('data'=>$response));
}

存在两个核心问题:

  1. get方法的参数传递错误:第二个参数是请求参数数组,直接传$request->input()会导致参数拼接异常,应该单独提取q关键词。
  2. 返回json_encode包装后的字符串:无法直接在视图中作为数组遍历,导致后续视图处理出错。

视图代码(尝试过的写法)

@foreach ($data as $item)
    {{$item['d']}}
@endforeach

得到JSON片段的原因是$data并非预期的数组结构,且没有定位到API响应中真正的条目数组(d字段)。

另外尝试直接返回视图:

return view('view',['data'=>$response]);

出现Illegal offset type错误,是因为直接遍历整个API响应对象,而没有定位到d这个数组字段,导致类型不匹配。

解决方案

1. 修正控制器代码

public function api(Request $request)
{
    // 单独提取查询关键词,避免参数混乱
    $query = $request->input('q');

    $response = Http::withHeaders([
        "x-rapidapi-host"=> "xxxxxxxxx",
        "x-rapidapi-key"=> "xxxxxxxxxxx",
    ])->get("https://imdb8.p.rapidapi.com/auto-complete", [
        'q' => $query // 正确传递查询参数
    ])->json();

    // 直接传递API返回的数组到视图,无需额外JSON编码
    return view('view', ['apiData' => $response]);
}

2. 修正Blade视图代码

API响应的影视条目都在d字段(数组类型),需要遍历这个字段才能正确展示数据:

@if(isset($apiData['d']) && count($apiData['d']) > 0)
    @foreach($apiData['d'] as $item)
        <div class="media-item">
            <h3>{{ $item['l'] }}</h3>
            <p>类型:{{ $item['q'] }}</p>
            <p>主演:{{ $item['s'] ?? '暂无信息' }}</p>
            <!-- 展示海报,先判断字段是否存在避免报错 -->
            @if(isset($item['i']['imageUrl']))
                <img src="{{ $item['i']['imageUrl'] }}" alt="{{ $item['l'] }}" style="width: 200px;">
            @endif
            <!-- 可选:展示预告片信息 -->
            @if(isset($item['v']) && count($item['v']) > 0)
                <h4>预告片:</h4>
                @foreach($item['v'] as $trailer)
                    <p>{{ $trailer['l'] ?? '无标题' }} - 时长:{{ $trailer['s'] ?? '未知' }}</p>
                @endforeach
            @endif
        </div>
    @endforeach
@else
    <p>未找到相关内容</p>
@endif

关键说明

  • 必须用isset()判断字段是否存在,防止API返回字段缺失导致的错误
  • 核心遍历对象是$apiData['d'],而不是整个API响应对象
  • 不要对API返回的数组做额外json_encode处理,直接传递数组到视图即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:25:16