Installation Add the bundle via Composer:
composer require cwd/youtube-bundle
Enable it in config/bundles.php (Symfony) or config/app.php (Laravel via Symfony bridge):
return [
// ...
Cwd\YouTubeBundle\CwdYouTubeBundle::class => ['all' => true],
];
Configuration Publish the default config:
php artisan vendor:publish --provider="Cwd\YouTubeBundle\CwdYouTubeBundle" --tag="config"
Update config/cwd_youtube.php with your YouTube API key and default settings (e.g., language, region).
First Use Case: Fetch a Video
Inject the YouTubeClient service into a controller or service:
use Cwd\YouTubeBundle\Client\YouTubeClient;
class VideoController extends Controller {
public function __construct(private YouTubeClient $client) {}
public function show(string $videoId) {
$video = $this->client->getVideo($videoId);
return view('video.show', ['video' => $video]);
}
}
Call the route (e.g., /video/{id}) to display video metadata (title, description, thumbnail, etc.).
Video Operations
$video = $client->getVideo('dQw4w9WgXcQ'); // Returns Video object
$results = $client->search('laravel tutorials', ['maxResults' => 5]);
$playlist = $client->getPlaylist('PL123');
$videos = $playlist->getVideos(); // Lazy-loaded
Channel Management
$channel = $client->getChannel('UC123');
$uploads = $channel->getUploadPlaylist()->getVideos();
Subscription Handling
$client->subscribeToChannel('UC456', $userToken);
Caching
Enable caching in config (cache: true) to avoid API rate limits:
$client->setCacheTTL(3600); // Cache for 1 hour
Laravel Blade Views Render video thumbnails/embeds:
<img src="{{ $video->getThumbnailUrl('maxres') }}" alt="{{ $video->title }}">
<iframe width="560" height="315"
src="https://www.youtube.com/embed/{{ $video->id }}"
frameborder="0"></iframe>
API Rate Limits Monitor quota usage via:
$quota = $client->getQuota();
if ($quota->remaining < 10) {
// Fallback or notify admin
}
Event Listeners
Extend the bundle by listening to cwd.youtube.video.fetched events:
public function handle(VideoFetchedEvent $event) {
$video = $event->getVideo();
// Log, analyze, or transform data
}
API Key Restrictions
https://www.googleapis.com/auth/youtube.readonly (for public data)https://www.googleapis.com/auth/youtube (for OAuth actions like subscriptions).config/cwd_youtube.php for api_key and validate via Google Cloud Console.Rate Limits
cache: true) and adjust cache_ttl (default: 300s).Deprecated Methods
getService() to access the underlying Google_Service_YouTube for raw API calls if needed.OAuth Flow
$client->setAuthToken($userToken); // Token from Google OAuth flow
encryption or sanctum).Enable Debug Mode
Set debug: true in config to log API responses:
'debug' => env('APP_DEBUG', false),
Check logs in storage/logs/laravel.log.
Common Errors
| Error | Cause | Solution |
|---|---|---|
Invalid API Key |
Wrong key or disabled API | Regenerate key in Google Cloud Console |
Quota Exceeded |
No caching or exceeded limits | Enable caching or upgrade quota |
Invalid Credentials |
Missing OAuth token | Implement OAuth2 flow |
Resource Not Found |
Invalid video/channel ID | Validate IDs (e.g., UC123 vs dQw4w9WgXcQ) |
Custom Responses
Override the Video/Playlist classes to add fields:
class ExtendedVideo extends \Cwd\YouTubeBundle\Entity\Video {
public function getViewsFormatted(): string {
return number_format($this->viewCount);
}
}
Bind your class in services.yaml (Symfony) or AppServiceProvider (Laravel).
Add Endpoints
Extend the bundle’s YouTubeClient via traits or decorators:
class CustomYouTubeClient extends YouTubeClient {
public function getTrendingVideos(string $regionCode = 'US') {
return $this->getService()->videos->listVideos([
'part' => 'snippet',
'chart' => 'mostPopular',
'regionCode' => $regionCode,
]);
}
}
Queue Long-Running Tasks Offload heavy operations (e.g., fetching 1000+ videos) to Laravel queues:
dispatch(new FetchVideosJob($client, $playlistId));
How can I help you explore Laravel packages today?