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 approachStorage::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.
