Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Youtube Bundle Laravel Package

cwd/youtube-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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],
    ];
    
  2. 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).

  3. 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.).


Implementation Patterns

Core Workflows

  1. Video Operations

    • Fetch a single video:
      $video = $client->getVideo('dQw4w9WgXcQ'); // Returns Video object
      
    • Search videos:
      $results = $client->search('laravel tutorials', ['maxResults' => 5]);
      
    • List playlists/videos:
      $playlist = $client->getPlaylist('PL123');
      $videos = $playlist->getVideos(); // Lazy-loaded
      
  2. Channel Management

    • Fetch a channel’s uploads:
      $channel = $client->getChannel('UC123');
      $uploads = $channel->getUploadPlaylist()->getVideos();
      
  3. Subscription Handling

    • Subscribe/unsubscribe (requires OAuth):
      $client->subscribeToChannel('UC456', $userToken);
      
  4. Caching Enable caching in config (cache: true) to avoid API rate limits:

    $client->setCacheTTL(3600); // Cache for 1 hour
    

Integration Tips

  • 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
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Restrictions

    • Ensure your YouTube API key has enabled the following scopes:
      • https://www.googleapis.com/auth/youtube.readonly (for public data)
      • https://www.googleapis.com/auth/youtube (for OAuth actions like subscriptions).
    • Debug: Check config/cwd_youtube.php for api_key and validate via Google Cloud Console.
  2. Rate Limits

    • Uncached requests hit YouTube’s quota limits (10,000 units/day by default).
    • Fix: Enable caching (cache: true) and adjust cache_ttl (default: 300s).
  3. Deprecated Methods

    • The bundle may lag behind YouTube API v3 updates. Check the official docs for breaking changes.
    • Tip: Use getService() to access the underlying Google_Service_YouTube for raw API calls if needed.
  4. OAuth Flow

    • For user-specific actions (e.g., subscriptions), implement OAuth2 via:
      $client->setAuthToken($userToken); // Token from Google OAuth flow
      
    • Gotcha: Store tokens securely (e.g., Laravel’s encryption or sanctum).

Debugging

  • 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)

Extension Points

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

  2. 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,
            ]);
        }
    }
    
  3. Queue Long-Running Tasks Offload heavy operations (e.g., fetching 1000+ videos) to Laravel queues:

    dispatch(new FetchVideosJob($client, $playlistId));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log