Laravel Tutorials

Simplifying Stream Handling with Laravel's resource Method

Published
Simplifying Stream Handling with Laravel's resource Method image

Laravel's HTTP Client now includes a resource() method that streamlines working with response streams, eliminating the verbose setup previously required for stream operations.

Before this enhancement, converting HTTP responses to streams required multiple steps and additional imports:

$response = Http::get($documentUrl);
$stream = StreamWrapper::getResource($response->toPsrResponse()->getBody());
Storage::writeStream('document.pdf', $stream);

The new approach reduces this to a single method call, making stream handling more intuitive and readable.

$response = Http::get($documentUrl);
Storage::writeStream('document.pdf', $response->resource());

Here's a file backup service that demonstrates practical stream usage:

class BackupService
{
    public function downloadRemoteBackup(string $backupUrl, string $destinationPath)
    {
        try {
            $this->validateBackupUrl($backupUrl);
            
            $response = Http::timeout(300)->get($backupUrl);
            
            if ($response->failed()) {
                throw new BackupDownloadException("Failed to retrieve backup from {$backupUrl}");
            }
            
            $fileSize = $response->header('Content-Length');
            $this->logBackupStart($backupUrl, $fileSize);
            
            Storage::disk('backups')->writeStream(
                $destinationPath,
                $response->resource()
            );
            
            $this->verifyBackupIntegrity($destinationPath, $fileSize);
            $this->logBackupCompletion($destinationPath);
            
            return true;
            
        } catch (Exception $e) {
            $this->logBackupError($backupUrl, $e->getMessage());
            throw new BackupProcessingException("Backup operation failed: {$e->getMessage()}");
        }
    }
    
    public function syncMediaLibrary(array $mediaUrls)
    {
        $results = [];
        
        foreach ($mediaUrls as $url) {
            $filename = basename(parse_url($url, PHP_URL_PATH));
            
            try {
                $response = Http::get($url);
                
                if ($response->successful()) {
                    Storage::disk('media')->writeStream(
                        "library/{$filename}",
                        $response->resource()
                    );
                    
                    $results[$url] = 'success';
                } else {
                    $results[$url] = 'failed';
                }
                
            } catch (Exception $e) {
                $results[$url] = 'error: ' . $e->getMessage();
            }
        }
        
        return $results;
    }
    
    private function validateBackupUrl(string $url)
    {
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            throw new InvalidArgumentException("Invalid backup URL provided");
        }
    }
    
    private function verifyBackupIntegrity(string $path, $expectedSize)
    {
        $actualSize = Storage::disk('backups')->size($path);
        
        if ($expectedSize && $actualSize !== (int) $expectedSize) {
            throw new BackupIntegrityException("File size mismatch during backup verification");
        }
    }
}

The resource() method simplifies file operations and reduces boilerplate code when working with HTTP response streams in Laravel applications.

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 →
PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support image

PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support

Read article
Insert Middleware Before or After Existing Laravel Middleware image

Insert Middleware Before or After Existing Laravel Middleware

Read article
Laravel Herd 2: Coding Agents, Workspaces, and Cloud Deploys image

Laravel Herd 2: Coding Agents, Workspaces, and Cloud Deploys

Read article
Strict Request Input Casting in Laravel image

Strict Request Input Casting in Laravel

Read article
Prevent Duplicate File Uploads With Laravel Storage Dedupler image

Prevent Duplicate File Uploads With Laravel Storage Dedupler

Read article
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article