Laravel Tutorials

Simplified Stream Response Handling in Laravel

Published
Simplified Stream Response Handling in Laravel image

Working with HTTP streams in Laravel has traditionally involved multiple steps and conversions, especially when dealing with file downloads or transfers. Laravel's new resource() method streamlines this process, reducing complex stream handling to a single method call.

The method is particularly valuable when downloading files from external sources and storing them in your application's storage system, eliminating the need for temporary files or complex stream conversions.

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

// Old approach required multiple conversions
$response = Http::get($url);
Storage::put('file.pdf', StreamWrapper::getResource(
    $response->toPsrResponse()->getBody()
));

// New streamlined approach
Storage::put('file.pdf', Http::get($url)->resource());

Let's explore a practical example of a document processing service:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use App\Exceptions\DocumentProcessingException;

class DocumentProcessor
{
    public function processRemoteDocument(string $documentUrl, string $reference)
    {
        try {
            $response = Http::timeout(30)->get($documentUrl);
            
            if (!$response->successful()) {
                throw new DocumentProcessingException(
                    "Failed to fetch document: {$response->status()}"
                );
            }
            // Store the original document
            $originalPath = "documents/{$reference}/original.pdf";
            Storage::put($originalPath, $response->resource());
            // Create a backup copy
            Storage::disk('backup')->writeStream(
                $originalPath,
                Storage::readStream($originalPath)
            );
            return [
                'reference' => $reference,
                'size' => Storage::size($originalPath),
                'path' => $originalPath
            ];
        } catch (Exception $e) {
            Log::error('Document processing failed', [
                'url' => $documentUrl,
                'reference' => $reference,
                'error' => $e->getMessage()
            ]);
            
            throw $e;
        }
    }
}

The resource() method simplifies stream handling in Laravel applications, making file operations more straightforward and reducing the complexity of your code.

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 →
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
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article