### Package Installation and Configuration Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Commands to install the package via Composer and publish the configuration file, followed by the required environment variables for Google API credentials. ```bash composer require mokhosh/laravel-youtube-api php artisan vendor:publish --tag='youtube-api' ``` ```env GOOGLE_APP_NAME=your-app-name GOOGLE_CLIENT_ID=your-client-id GOOGLE_CLIENT_SECRET=your-client-secret GOOGLE_API_KEY=your-api-key GOOGLE_REDIRECT_URL=https://your-app.com/youtube/callback ``` -------------------------------- ### Install Laravel YouTube API Package Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Installs the laravel-youtube-api package using Composer and adds the service provider to the Laravel application's configuration. ```shell composer require mokhosh/laravel-youtube-api ``` ```php Mokhosh\LaravelYoutubeApi\LaravelYoutubeApiServiceProvider::class ``` ```shell php artisan vendor:publish --tag='youtube-api' ``` -------------------------------- ### Start YouTube Event Stream Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Starts a YouTube event stream. This process involves three steps: sending the stream to the server URL, testing the stream status, and finally, initiating the live stream. It requires an authentication token, YouTube event ID, and a broadcast status ('testing' or 'live'). ```php $ytEventObj = new LiveStreamService(); /** * $broadcastStatus - ["testing", "live"] * Starting the event takes place in 3 steps * 1. Start sending the stream to the server_url via server_key recieved as a response in creating the event via the encoder of your choice. * 2. Once stream sending has started, stream test should be done by passing $broadcastStatus="testing" & it will return response for stream status. * 3. If transitioEvent() returns successfull for testing broadcast status, then start live streaming your video by passing $broadcastStatus="live" * & in response it will return us the stream status. */ $streamStatus = $ytEventObj->transitionEvent($authToken, $youtubeEventId, $broadcastStatus); ``` -------------------------------- ### List YouTube Video by ID (PHP) Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md This example shows how to retrieve details for a specific YouTube video using its ID. It utilizes the `videosListById` method of the `VideoService` class, specifying the desired parts of the video resource and the video ID. ```php $part ='snippet,contentDetails,id,statistics'; $params =array('id'=>'xyzgh'); $videoServiceObject = new VideoService; $response = $videoServiceObject->videosListById($part, $params); ``` -------------------------------- ### GET /channels Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Retrieves channel details by channel ID or username. ```APIDOC ## GET /channels ### Description Retrieves channel details by channel ID(s) without requiring authentication. Supports multiple channels via comma-separated IDs. ### Method GET ### Parameters #### Query Parameters - **part** (string) - Required - The parts of the channel resource to return (e.g., 'id,snippet,statistics'). - **id** (string) - Optional - Comma-separated list of channel IDs. - **forUsername** (string) - Optional - The YouTube username to look up. ### Response #### Success Response (200) - **items** (array) - List of channel objects containing snippet and statistics data. #### Response Example { "items": [ { "snippet": { "title": "Google Developers" }, "statistics": { "subscriberCount": "1000000" } } ] } ``` -------------------------------- ### Get Channel Details by Auth Token Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Retrieves the details of the authenticated user's channel using their provided authorization token. This is useful for accessing information specific to the logged-in user. ```php $channelServiceObject = new ChannelService; $channelDetails = $channelServiceObject->getChannelDetails($authToken); ``` -------------------------------- ### Get Channel Subscription List Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Retrieves a list of channels that the authenticated user is subscribed to. The '$params' array can be used to specify the target channel ID and the desired total number of results. The function handles pagination internally to fetch all requested results. ```php /* * $params array('channelId'=>'', 'totalResults'= 10) * totalResults is different of maxResults from Google Api. * totalResults = the amount of results you want * maxResults = max of results PER PAGE. We don't need this parameter here since it will loop until it gets all the results you want. */ $channelServiceObject = new ChannelService; $channelDetails = $channelServiceObject->subscriptionByChannelId($params); ``` -------------------------------- ### Get Authenticated Channel Details with Statistics Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Retrieves detailed information about the authenticated user's YouTube channel, including statistics and branding settings. Requires a valid user token. Returns an array of channel details or null on failure. ```php youtube_token, true); try { $channelDetails = $channelService->getChannelDetails($userToken); if ($channelDetails) { // Channel details returned as array $channelId = $channelDetails['id']; $title = $channelDetails['snippet']['title']; $description = $channelDetails['snippet']['description']; $thumbnail = $channelDetails['snippet']['thumbnails']['high']['url']; $subscriberCount = $channelDetails['statistics']['subscriberCount']; $viewCount = $channelDetails['statistics']['viewCount']; // Store channel info $user->update([ 'youtube_channel_id' => $channelId, 'youtube_channel_name' => $title, 'youtube_subscribers' => $subscriberCount ]); } } catch (Exception $e) { Log::error('Failed to get channel details: ' . $e->getMessage()); } ``` -------------------------------- ### Delete YouTube Video (PHP) Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md This example demonstrates how to delete a YouTube video from a channel using its ID. It requires the Google OAuth token and the `videoId` of the video to be deleted, utilizing the `deleteVideo` method of the `VideoService` class. ```php $videoServiceObject = new VideoService; $response = $videoServiceObject->deleteVideo($googleToken, $videoId); ``` -------------------------------- ### Get Channel Details by Channel ID Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Retrieves details for one or more YouTube channels using their IDs. This method does not require an authorization token. You can specify which details to retrieve using the '$part' parameter and provide channel IDs or a username in the '$params' array. ```php /** * [channelsListById -gets the channnel details and ] * $part 'id,snippet,contentDetails,status, statistics, contentOwnerDetails, brandingSettings' * $params [array channels id(comma separated ids ) or you can get ('forUsername' => 'GoogleDevelopers')] */ $part = 'id,snippet'; $params = array('id'=> 'channel_1_id,channel_2_id'); $channelServiceObject = new ChannelService; $channelDetails = $channelServiceObject->channelsListById($part, $params); ``` -------------------------------- ### Get Paginated Channel Subscriptions Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Retrieves a paginated list of subscriptions for a given YouTube channel ID. Automatically handles pagination to fetch a specified total number of results. Requires channel ID and total results count as parameters. Returns an array of subscription resources. ```php 'UC_x5XG1OV2P6uZZ5FSM9Ttw', 'totalResults' => 100 // Number of subscriptions to retrieve ]; try { $subscriptions = $channelService->subscriptionByChannelId($params); // Returns array of subscribed channel resource IDs foreach ($subscriptions as $subscription) { echo "Subscribed to: " . $subscription['channelId'] . "\n"; echo "Kind: " . $subscription['kind'] . "\n"; } // Example output: // [ // ['kind' => 'youtube#channel', 'channelId' => 'UCxyz123'], // ['kind' => 'youtube#channel', 'channelId' => 'UCabc456'], // ] } catch (Exception $e) { Log::error('Failed to get subscriptions: ' . $e->getMessage()); } ``` -------------------------------- ### Stop YouTube Event Stream Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Stops a YouTube event stream. Once the live streaming has started successfully, this function can be used to end the stream by setting the broadcast status to 'complete'. It requires an authentication token, YouTube event ID, and the broadcast status. ```php $ytEventObj = new LiveStreamService(); /** * $broadcastStatus - ["complete"] * Once live streaming gets started succesfully. We can stop the streaming the video by passing broadcastStatus="complete" and in response it will give us the stream status. */ $ytEventObj->transitionEvent($authToken, $youtubeEventId, $broadcastStatus); // $broadcastStatus = ["complete"] ``` -------------------------------- ### POST /live-broadcasts/transition Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Transitions the state of a live broadcast through testing, live streaming, and completion phases. ```APIDOC ## POST /live-broadcasts/transition ### Description Transitions the state of a live broadcast through testing, live streaming, and completion phases. Must be called in sequence: testing → live → complete. ### Method POST ### Parameters #### Request Body - **userToken** (array) - Required - The user's OAuth credentials. - **youtubeEventId** (string) - Required - The ID of the YouTube event. - **status** (string) - Required - The target status: 'testing', 'live', or 'complete'. ### Request Example { "youtubeEventId": "abc123xyz", "status": "live" } ### Response #### Success Response (200) - **status** (boolean) - Returns true if the transition was successful. ``` -------------------------------- ### Create YouTube Live Event with Laravel Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Provides code to create a new YouTube live streaming event using the `LiveStreamService`. It outlines the required data format for the event, including title, description, start/end times, privacy status, and optional parameters. The response contains details necessary for setting up the live stream. ```php "", "description" => "", "thumbnail_path" => "", // Optional "event_start_date_time" => "", "event_end_date_time" => "", // Optional "time_zone" => "", 'privacy_status' => "", // default: "public" OR "private" "language_name" => "", // default: "English" "tag_array" => "" // Optional and should not be more than 500 characters ); $ytEventObj = new LiveStreamService(); /** * The broadcast function returns array of details from YouTube. * Store this information & will be required to supply to youtube * for live streaming using encoder of your choice. */ $response = $ytEventObj->broadcast($authToken, $data); if ( !empty($response) ) { $youtubeEventId = $response['broadcast_response']['id']; $serverUrl = $response['stream_response']['cdn']->ingestionInfo->ingestionAddress; $serverKey = $response['stream_response']['cdn']->ingestionInfo->streamName; } ``` -------------------------------- ### Google Authentication with Laravel YouTube API Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Demonstrates how to initiate the Google OAuth flow to authenticate users for YouTube API access. It covers generating the authorization URL, fetching the authorization code, and exchanging it for an access token and channel details. ```php getLoginUrl('email','identifier'); $code = Input::get('code'); $identifier = Input::get('state'); $authObject = new AuthenticateService; $authResponse = $authObject->authChannelWithCode($code); // $authResponse['token'] (Channel Token) // $authResponse['channel_details'] // $authResponse['live_streaming_status'] (enabled or disabled) ``` -------------------------------- ### AuthenticateService OAuth Flow Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Demonstrates how to generate a Google OAuth login URL and handle the callback to exchange an authorization code for an access token and channel details. ```php getLoginUrl('user@gmail.com', 'user_123'); return redirect($authUrl); public function handleCallback(Request $request) { $code = $request->get('code'); $identifier = $request->get('state'); $authService = new AuthenticateService(); $authResponse = $authService->authChannelWithCode($code); User::where('id', $identifier)->update([ 'youtube_token' => json_encode($authResponse['token']) ]); return redirect('/dashboard')->with('success', 'YouTube connected!'); } ``` -------------------------------- ### CaptionService::captionsListById Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Lists all available captions/subtitles for a video. ```APIDOC ## GET /videos/{videoId}/captions ### Description Lists all available captions/subtitles for a video. ### Method GET ### Endpoint /videos/{videoId}/captions ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to list captions for. #### Query Parameters - **part** (string) - Optional - Specifies which parts of the caption resource to return. - **params** (object) - Optional - Additional parameters for filtering captions. ### Response #### Success Response (200) - **items** (array) - An array of caption resources. - **id** (string) - The ID of the caption track. - **snippet** (object) - Snippet containing caption details: - **language** (string) - The language of the caption. - **name** (string) - The name of the caption track. - **trackKind** (string) - The kind of caption track ('standard', 'ASR', 'forced'). #### Response Example ```json { "items": [ { "id": "caption123", "snippet": { "language": "en", "name": "English Subtitles", "trackKind": "standard" } } ] } ``` ``` -------------------------------- ### Transition YouTube Live Broadcast State Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Transitions a live broadcast through testing, live, and complete phases. Requires sequential execution to ensure the broadcast state is updated correctly on YouTube and the local database. ```php youtube_token, true); $youtubeEventId = 'abc123xyz'; try { $testStatus = $liveStream->transitionEvent($userToken, $youtubeEventId, 'testing'); if ($testStatus) { $liveStatus = $liveStream->transitionEvent($userToken, $youtubeEventId, 'live'); if ($liveStatus) { LiveEvent::where('youtube_event_id', $youtubeEventId) ->update(['status' => 'live', 'started_at' => now()]); } } } catch (Exception $e) { Log::error('Failed to transition broadcast: ' . $e->getMessage()); } $completeStatus = $liveStream->transitionEvent($userToken, $youtubeEventId, 'complete'); if ($completeStatus) { LiveEvent::where('youtube_event_id', $youtubeEventId) ->update(['status' => 'completed', 'ended_at' => now()]); } ``` -------------------------------- ### AuthenticateService::getLoginUrl Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Generates a Google OAuth URL for user authorization and handles the subsequent callback to exchange the authorization code for an access token. ```APIDOC ## GET /youtube/auth/login ### Description Generates a Google OAuth URL that users visit to authorize your application to access their YouTube account. ### Method GET ### Endpoint /youtube/auth/login ### Parameters #### Query Parameters - **email_hint** (string) - Optional - Pre-fills the email field on the Google login page. - **identifier** (string) - Optional - Custom state parameter to track the user session. ### Request Example $authService->getLoginUrl('user@gmail.com', 'user_123'); ### Response #### Success Response (200) - **auth_url** (string) - The URL to redirect the user to for Google authorization. #### Response Example { "auth_url": "https://accounts.google.com/o/oauth2/auth?..." } ``` -------------------------------- ### Add Code to Call API Class (PHP) Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md This snippet demonstrates how to include the necessary namespace and class for utilizing the VideoService from the Mokhosh Laravel YouTube API package. It sets up the foundation for subsequent API calls. ```php "", * 'description'=>"", * 'tags'=>"", * 'category_id'=>"", * 'video_status'=>"") */ $videoServiceObject = new VideoService; $response = $videoServiceObject->uploadVideo($googleToken, $videoPath, $data); ``` -------------------------------- ### Rate YouTube Video (PHP) Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md This snippet shows how to rate a YouTube video by applying a like, dislike, or removing any previous rating. It uses the `videosRate` method, requiring the Google OAuth token, the `videoId`, and the desired rating ('like', 'dislike', or 'none'). ```php # rating 'like' or 'dislike' or 'none' $videoServiceObject = new VideoService; $response = $videoServiceObject->videosRate($googleToken, $videoId, $rating); ``` -------------------------------- ### Import Channel Service Class Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Imports the ChannelService class from the Mokhosh Laravel YouTube API package. This is a prerequisite for using any of the channel-related functionalities. ```php youtube_token, true); $eventData = [ 'title' => 'My Live Stream', 'description' => 'Join me for this exciting live broadcast!', 'event_start_date_time' => '2024-03-15 18:00:00', 'time_zone' => 'America/New_York', 'privacy_status' => 'public', 'language_name' => 'English', 'tag_array' => ['gaming', 'live', 'stream'] ]; try { $response = $liveStream->broadcast($userToken, $eventData); if ($response) { $youtubeEventId = $response['broadcast_response']['id']; $serverUrl = $response['stream_response']['cdn']->ingestionInfo->ingestionAddress; $streamKey = $response['stream_response']['cdn']->ingestionInfo->streamName; } } catch (Exception $e) { Log::error('Failed to create broadcast: ' . $e->getMessage()); } ``` -------------------------------- ### Update Channel Branding Settings Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Updates the branding settings and preferences for a YouTube channel. This function requires the Google authentication token and an array of properties containing the specific settings to be updated, such as channel description, keywords, and featured channels. ```php /* * $properties array('id' => '', * 'brandingSettings.channel.description' => '', * 'brandingSettings.channel.keywords' => '', * 'brandingSettings.channel.defaultLanguage' => '', * 'brandingSettings.channel.defaultTab' => '', * 'brandingSettings.channel.moderateComments' => '', * 'brandingSettings.channel.showRelatedChannels' => '', * 'brandingSettings.channel.showBrowseView' => '', * 'brandingSettings.channel.featuredChannelsTitle' => '', * 'brandingSettings.channel.featuredChannelsUrls[]' => '', * 'brandingSettings.channel.unsubscribedTrailer' => '') */ $channelServiceObject = new ChannelService; $response = $channelServiceObject->updateChannelBrandingSettings($googleToken, $properties); ``` -------------------------------- ### Add Subscription to Channel Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Adds a subscription to a YouTube channel for the authorized user. Requires an array of properties specifying the subscription details (like channel ID and kind) and an authentication token. Optional parameters can also be provided. ```php /* * properties array('snippet.resourceId.kind' => 'youtube#channel','snippet.resourceId.channelId' => 'UCqIOaYtQak4-FD2-yI7hFkw') */ $channelServiceObject = new ChannelService; $response = $channelServiceObject->addSubscriptions($properties, $token, $part='snippet', $params=[]); ``` -------------------------------- ### Update Channel Branding Settings in Laravel Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Updates channel branding properties such as description, keywords, and display preferences. Requires an authenticated user token and specific branding parameters. ```php youtube_token, true); $properties = [ 'id' => 'UCxxxxYourChannelId', 'brandingSettings.channel.description' => 'Updated channel description with keywords.', 'brandingSettings.channel.keywords' => 'gaming tutorials streaming', 'brandingSettings.channel.defaultLanguage' => 'en', 'brandingSettings.channel.moderateComments' => true, 'brandingSettings.channel.showRelatedChannels' => true, 'brandingSettings.channel.showBrowseView' => true, 'brandingSettings.channel.featuredChannelsTitle' => 'Channels I Recommend', 'brandingSettings.channel.featuredChannelsUrls[]' => 'UCabc123,UCdef456', 'brandingSettings.channel.unsubscribedTrailer' => 'videoId123' ]; $part = 'brandingSettings'; $params = []; try { $result = $channelService->updateChannelBrandingSettings($userToken, $properties, $part, $params); if ($result) { echo "Channel branding updated successfully!"; } } catch (Exception $e) { Log::error('Failed to update branding: ' . $e->getMessage()); } ``` -------------------------------- ### Subscribe to a YouTube Channel Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Subscribes the authenticated user's channel to another YouTube channel. Requires the target channel ID and a valid user token. Returns a response object with the subscription ID on success, or throws an exception on failure. ```php youtube_token, true); // Subscribe to a channel $properties = [ 'snippet.resourceId.kind' => 'youtube#channel', 'snippet.resourceId.channelId' => 'UCqIOaYtQak4-FD2-yI7hFkw' // Target channel ID ]; try { $response = $channelService->addSubscriptions($properties, $userToken); if ($response) { $subscriptionId = $response->id; echo "Successfully subscribed! Subscription ID: " . $subscriptionId; // Store subscription for later management Subscription::create([ 'user_id' => $user->id, 'subscription_id' => $subscriptionId, 'channel_id' => 'UCqIOaYtQak4-FD2-yI7hFkw' ]); } } catch (Exception $e) { // Handle duplicate subscription or other errors Log::error('Subscription failed: ' . $e->getMessage()); } ``` -------------------------------- ### LiveStreamService::broadcast Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Creates a new YouTube live streaming event and binds a stream to it, returning the necessary RTMP server URL and stream key for broadcasting software. ```APIDOC ## POST /youtube/live/broadcast ### Description Creates a new YouTube live streaming event with a bound stream. Returns broadcast details including the RTMP server URL and stream key. ### Method POST ### Endpoint /youtube/live/broadcast ### Parameters #### Request Body - **title** (string) - Required - Title of the live stream. - **description** (string) - Required - Description of the live stream. - **event_start_date_time** (string) - Required - Start time in YYYY-MM-DD HH:MM:SS format. - **privacy_status** (string) - Required - 'public', 'private', or 'unlisted'. - **time_zone** (string) - Required - Time zone for the event. ### Request Example { "title": "My Live Stream", "description": "Join me for this exciting live broadcast!", "event_start_date_time": "2024-03-15 18:00:00", "privacy_status": "public", "time_zone": "America/New_York" } ### Response #### Success Response (200) - **broadcast_response** (object) - Contains the YouTube event ID. - **stream_response** (object) - Contains the RTMP ingestion URL and stream key. #### Response Example { "broadcast_response": { "id": "yt_event_123" }, "stream_response": { "cdn": { "ingestionInfo": { "ingestionAddress": "rtmp://...", "streamName": "xxxx-xxxx" } } } } ``` -------------------------------- ### CaptionService::uploadCaption Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Uploads a caption/subtitle track to a video on the authenticated user's channel. ```APIDOC ## POST /videos/{videoId}/captions ### Description Uploads a caption/subtitle track to a video on the authenticated user's channel. ### Method POST ### Endpoint /videos/{videoId}/captions ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to upload the caption to. #### Request Body - **userToken** (object) - Required - Authentication token for the user. - **captionPath** (string) - Required - The local path to the caption file (e.g., SRT format). - **language** (string) - Required - The language code for the caption. - **name** (string) - Optional - The name of the caption track. ### Response #### Success Response (200) - **id** (string) - The ID of the uploaded caption track. #### Response Example ```json { "id": "newCaptionId456" } ``` ``` -------------------------------- ### Search YouTube Content by Keyword in Laravel Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Performs a search query on YouTube to find videos, channels, or playlists. Supports pagination and filtering by order, type, and result count. ```php 'laravel tutorial', 'maxResults' => 25, 'type' => 'video', 'order' => 'relevance' ]; $results = $videoService->searchListByKeyword($part, $params); foreach ($results->items as $item) { echo "Video ID: " . $item->id->videoId . "\n"; echo "Title: " . $item->snippet->title . "\n"; echo "Channel: " . $item->snippet->channelTitle . "\n"; echo "Thumbnail: " . $item->snippet->thumbnails->high->url . "\n"; echo "---\n"; } if (isset($results->nextPageToken)) { $params['pageToken'] = $results->nextPageToken; $nextPage = $videoService->searchListByKeyword($part, $params); } ``` -------------------------------- ### Upload Caption to YouTube Video - PHP Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Uploads a caption or subtitle track to a specific YouTube video on the authenticated user's channel. Requires user authentication token, video ID, caption file path, language, and a name for the caption. Handles potential errors during upload. ```php youtube_token, true); $videoId = 'abc123xyz'; $captionPath = storage_path('captions/english.srt'); $language = 'en'; $name = 'English Subtitles'; try { $response = $captionService->uploadCaption($userToken, $videoId, $captionPath, $language, $name); if ($response) { $captionId = $response->id; echo "Caption uploaded successfully! ID: " . $captionId; // Store caption reference Caption::create([ 'video_id' => $videoId, 'caption_id' => $captionId, 'language' => $language, 'name' => $name ]); } } catch (Exception $e) { Log::error('Caption upload failed: ' . $e->getMessage()); } ?> ``` -------------------------------- ### VideoService::videosRate Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Adds a like, dislike, or removes rating from a video using the authenticated user's account. ```APIDOC ## POST /videos/{videoId}/rate ### Description Adds a like, dislike, or removes rating from a video using the authenticated user's account. ### Method POST ### Endpoint /videos/{videoId}/rate ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to rate. #### Request Body - **userToken** (object) - Required - Authentication token for the user. - **rating** (string) - Required - The rating to apply ('like', 'dislike', or 'none'). ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating successful rating update. #### Response Example ```json { "message": "Rating updated successfully!" } ``` ``` -------------------------------- ### Update YouTube Live Event with Laravel Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Demonstrates how to update an existing YouTube live streaming event using the `LiveStreamService`. This function allows modification of event details and may also update the stream's ingestion URL and stream key, which should be saved if changed. ```php $ytEventObj = new LiveStreamService(); /** * The updateBroadcast response give details of the youtube_event_id,server_url and server_key. * The server_url & server_key gets updated in the process. (save the updated server_key and server_url). */ $response = $ytEventObj->updateBroadcast($authToken, $data, $youtubeEventId); ``` -------------------------------- ### List YouTube Video Captions - PHP Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Lists all available captions or subtitles for a given YouTube video. Requires the video ID and optionally accepts parameters to filter the results. Iterates through the captions and displays their details. ```php captionsListById($part, $videoId, $params); foreach ($captions->items as $caption) { echo "Caption ID: " . $caption->id . "\n"; echo "Language: " . $caption->snippet->language . "\n"; echo "Name: " . $caption->snippet->name . "\n"; echo "Track Kind: " . $caption->snippet->trackKind . "\n"; // standard, ASR, forced echo "---\n"; } ?> ``` -------------------------------- ### Retrieve Video Details by ID in Laravel Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Fetches detailed metadata, statistics, and content information for one or more YouTube videos using their unique IDs. This method does not require authentication. ```php 'dQw4w9WgXcQ']; $videos = $videoService->videosListById($part, $params); foreach ($videos->items as $video) { echo "Title: " . $video->snippet->title . "\n"; echo "Description: " . $video->snippet->description . "\n"; echo "Channel: " . $video->snippet->channelTitle . "\n"; echo "Published: " . $video->snippet->publishedAt . "\n"; echo "Duration: " . $video->contentDetails->duration . "\n"; echo "Views: " . $video->statistics->viewCount . "\n"; echo "Likes: " . $video->statistics->likeCount . "\n"; echo "Comments: " . $video->statistics->commentCount . "\n"; } $params = ['id' => 'dQw4w9WgXcQ,jNQXAC9IVRw,kJQP7kiw5Fk']; $multipleVideos = $videoService->videosListById($part, $params); ``` -------------------------------- ### Retrieve YouTube Channel Details Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Fetches channel information such as statistics and branding settings using channel IDs or usernames. This operation does not require authentication. ```php 'UC_x5XG1OV2P6uZZ5FSM9Ttw']; $channelDetails = $channelService->channelsListById($part, $params); foreach ($channelDetails->items as $channel) { echo "Channel: " . $channel->snippet->title . "\n"; echo "Subscribers: " . $channel->statistics->subscriberCount . "\n"; } // Get multiple channels $params = ['id' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw,UCVHFbqXqoYvEWM1Ddxl0QKg']; $multipleChannels = $channelService->channelsListById($part, $params); ``` -------------------------------- ### Upload Video to YouTube - PHP Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Uploads a video file to the authenticated user's YouTube channel with metadata and privacy settings. Supports resumable uploads for large files up to 128GB. Requires user authentication token and video file path. ```php youtube_token, true); $videoPath = storage_path('videos/my-video.mp4'); $videoData = [ 'title' => 'My Awesome Video', 'description' => 'Check out this amazing content! #hashtag', 'tags' => ['tutorial', 'laravel', 'php'], 'category_id' => '22', // 22 = People & Blogs, 24 = Entertainment, 28 = Science & Tech 'video_status' => 'public', // 'public', 'private', or 'unlisted' 'language' => 'en', 'audio_language' => 'en', 'chunk_size' => 1 * 1024 * 1024 // Optional: 1MB chunks (increase for faster uploads) ]; try { $response = $videoService->uploadVideo($userToken, $videoPath, $videoData); if ($response) { $videoId = $response->id; $videoUrl = "https://www.youtube.com/watch?v=" . $videoId; // Store uploaded video reference Video::create([ 'user_id' => $user->id, 'youtube_id' => $videoId, 'title' => $videoData['title'], 'url' => $videoUrl, 'status' => $videoData['video_status'] ]); echo "Video uploaded successfully: " . $videoUrl; } } catch (Exception $e) { Log::error('Video upload failed: ' . $e->getMessage()); } ?> ``` -------------------------------- ### VideoService::uploadVideo Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Uploads a video file to the authenticated user's YouTube channel with metadata and privacy settings. Supports resumable uploads for large files up to 128GB. ```APIDOC ## POST /videos ### Description Uploads a video file to the authenticated user's YouTube channel with metadata and privacy settings. Supports resumable uploads for large files up to 128GB. ### Method POST ### Endpoint /videos ### Parameters #### Request Body - **userToken** (object) - Required - Authentication token for the user. - **videoPath** (string) - Required - The local path to the video file. - **videoData** (object) - Required - Metadata for the video: - **title** (string) - Required - The title of the video. - **description** (string) - Optional - The description of the video. - **tags** (array) - Optional - An array of tags for the video. - **category_id** (string) - Optional - The YouTube category ID for the video. - **video_status** (string) - Optional - The privacy status of the video ('public', 'private', or 'unlisted'). - **language** (string) - Optional - The language of the video. - **audio_language** (string) - Optional - The audio language of the video. - **chunk_size** (integer) - Optional - The chunk size for resumable uploads in bytes. ### Request Example ```php { "title": "My Awesome Video", "description": "Check out this amazing content! #hashtag", "tags": ["tutorial", "laravel", "php"], "category_id": "22", "video_status": "public", "language": "en", "audio_language": "en", "chunk_size": 1048576 } ``` ### Response #### Success Response (200) - **id** (string) - The YouTube video ID. #### Response Example ```json { "id": "dQw4w9WgXcQ" } ``` ``` -------------------------------- ### Find Related Videos in Laravel Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Retrieves a list of videos related to a specific video ID, useful for building recommendation features. Allows filtering by region and language. ```php 'dQw4w9WgXcQ', 'type' => 'video', 'maxResults' => 10, 'regionCode' => 'US', 'relevanceLanguage' => 'en' ]; $relatedVideos = $videoService->relatedToVideoId($part, $params); echo "Videos related to the original:\n"; foreach ($relatedVideos->items as $video) { echo "- " . $video->snippet->title . " (" . $video->id->videoId . ")\n"; } ``` -------------------------------- ### Update YouTube Live Broadcast with Laravel Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Updates an existing YouTube live broadcast event including metadata like title, description, and schedule. It also handles the generation of new stream credentials and updates the local database. ```php youtube_token, true); $existingEventId = 'abc123xyz'; $updatedData = [ 'title' => 'Updated: My Live Stream - Now at 7PM!', 'description' => 'Time changed! Join me at the new time.', 'thumbnail_path' => '/path/to/new-thumbnail.jpg', 'event_start_date_time' => '2024-03-15 19:00:00', 'event_end_date_time' => '2024-03-15 21:00:00', 'time_zone' => 'America/New_York', 'privacy_status' => 'public', 'language_name' => 'English', 'tag_array' => ['gaming', 'live', 'updated'] ]; try { $response = $liveStream->updateBroadcast($userToken, $updatedData, $existingEventId); if ($response) { $newServerUrl = $response['stream_response']['cdn']->ingestionInfo->ingestionAddress; $newStreamKey = $response['stream_response']['cdn']->ingestionInfo->streamName; LiveEvent::where('youtube_event_id', $existingEventId)->update([ 'server_url' => $newServerUrl, 'stream_key' => $newStreamKey, 'updated_at' => now() ]); } } catch (Exception $e) { Log::error('Failed to update broadcast: ' . $e->getMessage()); } ``` -------------------------------- ### Rate YouTube Video - PHP Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Allows the authenticated user to like, dislike, or remove their rating from a YouTube video. Requires user authentication token and the video ID. Demonstrates liking, disliking, and removing a rating. ```php youtube_token, true); $videoId = 'dQw4w9WgXcQ'; try { // Like a video $videoService->videosRate($userToken, $videoId, 'like'); // Dislike a video $videoService->videosRate($userToken, $videoId, 'dislike'); // Remove rating (neither like nor dislike) $videoService->videosRate($userToken, $videoId, 'none'); echo "Rating updated successfully!"; } catch (Exception $e) { Log::error('Failed to rate video: ' . $e->getMessage()); } ?> ``` -------------------------------- ### Remove a YouTube Channel Subscription Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Removes a subscription from the authenticated user's channel using the subscription ID. Requires a valid user token and the subscription ID. Upon successful removal, it also deletes the corresponding local record. Throws an exception on failure. ```php youtube_token, true); $subscriptionId = 'xyz123subscriptionId'; // From addSubscriptions response try { $response = $channelService->removeSubscription($userToken, $subscriptionId); // Remove from local database Subscription::where('subscription_id', $subscriptionId)->delete(); echo "Successfully unsubscribed!"; } catch (Exception $e) { Log::error('Failed to remove subscription: ' . $e->getMessage()); } ``` -------------------------------- ### VideoService::deleteVideo Source: https://context7.com/mokhosh/laravel-youtube-api/llms.txt Deletes a video from the authenticated user's YouTube channel. ```APIDOC ## DELETE /videos/{videoId} ### Description Deletes a video from the authenticated user's YouTube channel. ### Method DELETE ### Endpoint /videos/{videoId} ### Parameters #### Path Parameters - **videoId** (string) - Required - The ID of the video to delete. #### Request Body - **userToken** (object) - Required - Authentication token for the user. ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating successful deletion. #### Response Example ```json { "message": "Video deleted successfully" } ``` ``` -------------------------------- ### Remove Subscription from Channel Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Removes a subscription from a YouTube channel for the authorized user. This action requires the authentication token and the specific subscription ID, which can be obtained from the channel's subscription list. ```php $response = $channelServiceObject->removeSubscription( $token, $subscriptionId); ``` -------------------------------- ### Delete YouTube Event Source: https://github.com/mokhosh/laravel-youtube-api/blob/master/README.md Deletes a YouTube event. Requires an authentication token for the channel and the YouTube event ID. No specific dependencies are mentioned beyond the YouTube API service object. ```php $ytEventObj->deleteEvent($authToken, $youtubeEventId); ```