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

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article