Laravel Tutorials

Download Files Easily with Laravel's HTTP sink Method

Published
Download Files Easily with Laravel's HTTP sink Method image

Laravel's sink method transforms file downloads through HTTP requests into a streamlined process, eliminating the need for complex file handling code. This approach creates a direct pipeline from remote resources to your local storage with minimal effort.

Http::sink(storage_path('download.zip'))
->get('https://example.com/example-file.zip');

By using the sink method, you bypass manual file writing processes and memory management concerns, allowing Laravel to handle the complexities of saving HTTP responses directly to disk.

class DownloadManager
{
public function downloadFile(string $url, string $filename)
{
return Http::sink(storage_path("downloads/{$filename}"))
->withHeaders([
'User-Agent' => 'MyApp/1.0',
'Accept' => '*/*'
])
->get($url);
}
 
public function downloadBackup(string $backupUrl, string $apiKey)
{
$timestamp = now()->format('Y-m-d-His');
 
return Http::sink(storage_path("backups/backup-{$timestamp}.zip"))
->withToken($apiKey)
->get($backupUrl);
}
 
public function downloadReportAsCsv(string $reportUrl)
{
return Http::sink(
storage_path('reports/latest.csv'),
withHeaders([
'Accept' => 'text/csv'
])
)->get($reportUrl);
}
}

The sink method shines when dealing with large files that shouldn't be loaded entirely into memory. Rather than consuming precious RAM resources, the content streams directly to disk, making it ideal for background jobs, automated backup systems, and scenarios with tight memory constraints. For instance, downloading a 1GB file becomes vastly more efficient as data writes straight to storage instead of buffering in application memory first.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article