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

Laravel 5.4使用alaouy/Youtube包获取视频时遇未定义属性错误

解决Laravel中alaouy/Youtube包访问videoId时的Undefined Property错误

Hey there, let's fix that frustrating "Undefined property" error you're hitting when trying to get the videoId from YouTube search results!

问题根源

The issue here is that YouTube's Search API (which the alaouy/Youtube package uses) returns multiple types of results by default — videos, channels, and playlists. Each result type has a different structure for the id field:

  • Videos have a videoId property under id
  • Channels use channelId instead
  • Playlists use playlistId

When you loop through all results and try to access $data->id->videoId directly, you'll hit an error on any non-video result because that property doesn't exist for them.

解决方案1:只搜索视频类型(推荐)

If you only care about video results, modify your controller code to restrict the search to just videos by adding the type parameter:

$videos = Youtube::search($search, ['type' => 'video']);
return view('search', compact('videos'));

Now every result in $videos will be a video, so $data->id->videoId will exist for every entry, and your original view code will work without errors.

解决方案2:兼容多种结果类型

If you need to keep all result types (videos, channels, playlists), update your view to check the result type before accessing the ID property:

@extends('welcome')
@section('content')
<ul>
    @foreach($videos as $data)
        <div class="well">
            @if($data->id->kind === 'youtube#video')
                Video ID: {{ $data->id->videoId }}
            @elseif($data->id->kind === 'youtube#channel')
                Channel ID: {{ $data->id->channelId }}
            @elseif($data->id->kind === 'youtube#playlist')
                Playlist ID: {{ $data->id->playlistId }}
            @endif
        </div>
    @endforeach
</ul>
@endsection

This checks the kind property of the id object to determine what type of result you're dealing with, then accesses the correct ID property accordingly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:47:28