Install Dependencies:
sudo apt install ffmpeg youtube-dl # Linux (Ubuntu/Debian)
For other OSes, ensure ffmpeg and youtube-dl are installed and accessible via CLI.
Install Package:
composer require devswebdev/devtube
Publish Config:
php artisan vendor:publish --provider="DevsWebDev\DevTube\DevTubeServiceProvider"
Verify config/devtube.php and update bin_path to match your system’s youtube-dl location (check with which youtube-dl).
First Use Case: Download a video from a URL and return it as a downloadable file:
use DevsWebDev\DevTube\Download;
$dl = new Download(
url: "https://www.youtube.com/watch?v=example",
format: "mp4",
download_path: storage_path('app/videos')
);
$mediaInfo = $dl->download()->first();
return response()->download($mediaInfo['file']->getPathname());
Basic Download:
Use the Download class to fetch and save media:
$dl = new Download($url, $format, $downloadPath);
$mediaInfo = $dl->download(); // Returns a collection of `MediaInfo` objects
$format: Supports formats like mp4, webm, or best (default).$downloadPath: Directory to save files (default: storage_path('app/devtube')).Batch Processing: Loop through multiple URLs:
$urls = ["url1", "url2"];
foreach ($urls as $url) {
$dl = new Download($url, "mp4");
$dl->download();
}
Streaming Responses: Serve downloaded files directly without saving to disk:
$dl = new Download($url, "mp4");
$mediaInfo = $dl->download()->first();
return response()->streamDownload(function () use ($mediaInfo) {
echo file_get_contents($mediaInfo['file']->getPathname());
});
FFmpeg Conversion:
Convert videos to audio (requires ffmpeg):
$dl = new Download($url, "mp3"); // Auto-converts if supported
$mediaInfo = $dl->download()->first();
Custom Paths:
Override default storage paths in config/devtube.php:
'download_path' => storage_path('custom/videos'),
'temp_path' => sys_get_temp_dir(),
Error Handling: Wrap downloads in try-catch to handle failures (e.g., invalid URLs, unsupported formats):
try {
$dl->download();
} catch (\Exception $e) {
Log::error("Download failed: " . $e->getMessage());
return back()->with('error', 'Failed to download video.');
}
Queue Jobs: Offload downloads to a queue (e.g., Laravel Queues) for long-running tasks:
Dispatch(new DownloadJob($url, $format));
Implement DownloadJob with DevTube\Download logic.
Middleware: Restrict access to download endpoints:
Route::middleware(['auth'])->group(function () {
Route::get('/download', [YoutubeDownloadController::class, 'download']);
});
Artisan Commands: Create a scheduled download task:
php artisan make:command DownloadVideos
Use DevTube\Download in the command to fetch videos periodically.
Testing:
Mock DevTube\Download in unit tests:
$mock = Mockery::mock(DevTube\Download::class);
$mock->shouldReceive('download')->andReturn(collect([...]));
Dependency Conflicts:
youtube-dl and ffmpeg are up-to-date. Outdated versions may fail to fetch modern video formats.apt/brew.Path Permissions:
storage/app/devtube or custom paths.chmod -R 775 storage/ or adjust config/devtube.php to use a writable directory.Unsupported URLs:
Memory Limits:
memory_limit.memory_limit in php.ini or stream files directly to the client.FFmpeg Missing:
mp3 or other formats, ensure ffmpeg is installed and in PATH.ffmpeg or set a custom path in config/devtube.php:
'ffmpeg_path' => '/usr/local/bin/ffmpeg',
Rate Limiting:
Log Output:
Enable verbose logging in config/devtube.php:
'verbose' => true,
Check Laravel logs (storage/logs/laravel.log) for youtube-dl output.
Manual Testing:
Test youtube-dl commands directly in the terminal to isolate issues:
youtube-dl --format mp4 "https://example.com"
Check Returned Data:
Inspect $mediaInfo for errors:
dd($mediaInfo->first()['error']); // May contain `youtube-dl` output
Environment-Specific Paths:
Use absolute paths in config/devtube.php to avoid issues across environments:
'bin_path' => '/full/path/to/youtube-dl',
Custom Formats:
Extend the package to support additional formats by modifying the Download class or creating a wrapper:
$dl = new Download($url, "custom_format");
$dl->setFfmpegArgs(['-vf', 'scale=640:480']); // Custom FFmpeg args
Metadata Extraction:
Parse MediaInfo objects to extract metadata (title, duration, etc.):
$title = $mediaInfo['title'];
$duration = $mediaInfo['duration'];
Storage Adapters: Replace the default storage logic to use S3 or other cloud storage:
$dl->setStorageAdapter(new S3Adapter());
Event Listeners: Trigger events after download (e.g., notify users, update a database):
event(new VideoDownloaded($mediaInfo));
Configuration Overrides: Dynamically override settings per request:
$dl->setOption('format', 'webm');
$dl->setOption('path', $customPath);
How can I help you explore Laravel packages today?