1. Go to this page and download the library: Download ekstremedia/laravel-youtube library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ekstremedia / laravel-youtube example snippets
use EkstreMedia\LaravelYouTube\Facades\YouTube;
// Authenticate user (redirect to Google)
return redirect()->to(YouTube::getAuthUrl());
// After authentication, upload a video
$video = YouTube::forUser(auth()->id())
->uploadVideo(
'/path/to/video.mp4',
[
'title' => 'My Amazing Video',
'description' => 'This is a great video!',
'tags' => ['laravel', 'youtube', 'api'],
'category_id' => '22',
'privacy_status' => 'public',
]
);
echo "Video uploaded: " . $video->watch_url;
// Method 1: Use the default (most recent) active token
YouTube::usingDefault()->uploadVideo($file, $metadata);
// Method 2: Use a specific channel by ID
YouTube::forChannel('UCxxxxxxxxxx')->uploadVideo($file, $metadata);
// Method 3: For legacy support, specify user ID
YouTube::forUser($userId)->uploadVideo($file, $metadata);
// In your Pi upload endpoint
use Ekstremedia\LaravelYouTube\Facades\YouTube;
Route::post('/api/pi/upload', function (Request $request) {
$request->validate([
'video' => 'oadVideo($file, [
'title' => "Pi Camera {$request->camera_id} - " . now()->format('Y-m-d H:i'),
'description' => 'Automated timelapse from Raspberry Pi',
'tags' => ['raspberry-pi', 'timelapse', $request->camera_id],
'privacy_status' => 'unlisted',
]);
return response()->json([
'success' => true,
'video_id' => $video->video_id,
'watch_url' => $video->watch_url,
]);
});
// Link to authentication page
<a href="{{ route('youtube.authorize') }}">Connect YouTube</a>
// Or use the configured path
<a href="/{{ config('youtube.routes.auth_page.path') }}">Authorize YouTube</a>
use EkstreMedia\LaravelYouTube\Services\AuthService;
$authService = app(AuthService::class);
// Generate OAuth URL with state for CSRF protection
$state = Str::random(40);
session(['youtube_oauth_state' => $state]);
$authUrl = $authService->getAuthUrl($state);
// In callback handler
if (request('state') !== session('youtube_oauth_state')) {
abort(403, 'Invalid state');
}
// Exchange code for tokens
$tokens = $authService->exchangeCode(request('code'));
use EkstreMedia\LaravelYouTube\Services\TokenManager;
$tokenManager = app(TokenManager::class);
// Store tokens after OAuth
$token = $tokenManager->storeToken(
$tokens,
$channelInfo,
auth()->id()
);
// Get active token for user
$token = $tokenManager->getActiveToken(auth()->id());
// Check if refresh needed (within 5 minutes of expiry)
if ($tokenManager->needsRefresh($token)) {
$newTokens = $authService->refreshAccessToken($token->refresh_token);
$tokenManager->updateToken($token, $newTokens);
}
// Handle multiple channels
$tokens = $tokenManager->getUserTokens(auth()->id());
foreach ($tokens as $token) {
echo "Channel: {$token->channel_title}\n";
}
// Create a new playlist
$playlist = YouTube::usingDefault()->createPlaylist('My Playlist', [
'description' => 'Collection of my favorite videos',
'privacy_status' => 'public', // private, public, unlisted
'tags' => ['favorites', 'collection'],
]);
// Get all playlists
$result = YouTube::usingDefault()->getPlaylists();
foreach ($result['playlists'] as $playlist) {
echo "{$playlist['title']} - {$playlist['item_count']} videos\n";
}
// Add video to playlist
YouTube::usingDefault()->addVideoToPlaylist(
'video-id',
'playlist-id',
0 // Position (0 = first)
);
// Get videos in a playlist
$result = YouTube::usingDefault()->getPlaylistVideos('playlist-id');
foreach ($result['videos'] as $video) {
echo "{$video['title']} (position: {$video['position']})\n";
}
// Update playlist
YouTube::usingDefault()->updatePlaylist('playlist-id', [
'title' => 'Updated Title',
'privacy_status' => 'public',
]);
// Delete playlist
YouTube::usingDefault()->deletePlaylist('playlist-id');
// Upload captions (supports SRT, VTT, TTML, SBV)
$caption = YouTube::usingDefault()->uploadCaption(
'video-id',
'en', // Language code
'/path/to/captions.srt',
[
'name' => 'English Subtitles',
'is_draft' => false,
]
);
// List all captions for a video
$captions = YouTube::usingDefault()->getCaptions('video-id');
foreach ($captions as $caption) {
echo "{$caption['name']} ({$caption['language']})\n";
}
// Update caption metadata or file
YouTube::usingDefault()->updateCaption(
'caption-id',
['name' => 'Updated English'],
'/path/to/new-captions.srt' // Optional: new file
);
// Download captions in different formats
$srt = YouTube::usingDefault()->downloadCaption('caption-id', 'srt');
$vtt = YouTube::usingDefault()->downloadCaption('caption-id', 'vtt');
file_put_contents('captions.srt', $srt);
// Delete captions
YouTube::usingDefault()->deleteCaption('caption-id');
// Create your own job
namespace App\Jobs;
use Ekstremedia\LaravelYouTube\Facades\YouTube;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class UploadYouTubeVideo implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public string $videoPath,
public array $metadata
) {}
public function handle(): void
{
$video = YouTube::usingDefault()->uploadVideo(
$this->videoPath,
$this->metadata
);
// Clean up temporary file
unlink($this->videoPath);
}
}
// Dispatch the job
UploadYouTubeVideo::dispatch(
videoPath: '/path/to/video.mp4',
metadata: [
'title' => 'Queued Upload',
'description' => 'Uploaded via queue',
'tags' => ['queued', 'background'],
'privacy_status' => 'private',
]
)->onQueue('media');