Home >Backend Development >PHP Tutorial >Simplified Stream Response Handling in Laravel
Laravel's streamlined approach to HTTP stream handling significantly simplifies file downloads and transfers. Previously, managing streams, particularly for file downloads from external sources, involved multiple steps and conversions. Now, the resource()
method offers a concise solution.
This is especially beneficial when saving files to your application's storage. The resource()
method eliminates the need for temporary files and complex stream manipulations.
Here's a comparison of the old and new methods:
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; // Older, more complex approach $response = Http::get($url); Storage::put('file.pdf', StreamWrapper::getResource( $response->toPsrResponse()->getBody() )); // New, simplified approach using resource() Storage::put('file.pdf', Http::get($url)->resource());
Let's examine a practical example within a document processing service:
<?php namespace App\Services; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; use App\Exceptions\DocumentProcessingException; use Exception; use Illuminate\Support\Facades\Log; class DocumentProcessor { public function processRemoteDocument(string $documentUrl, string $reference) { try { $response = Http::timeout(30)->get($documentUrl); if (!$response->successful()) { throw new DocumentProcessingException( "Document retrieval failed: {$response->status()}" ); } // Store the original document $originalPath = "documents/{$reference}/original.pdf"; Storage::put($originalPath, $response->resource()); // Create a backup Storage::disk('backup')->writeStream( $originalPath, Storage::readStream($originalPath) ); return [ 'reference' => $reference, 'size' => Storage::size($originalPath), 'path' => $originalPath ]; } catch (Exception $e) { Log::error('Document processing error', [ 'url' => $documentUrl, 'reference' => $reference, 'error' => $e->getMessage() ]); throw $e; } } }
The resource()
method dramatically simplifies stream handling in Laravel, resulting in cleaner, more efficient file operations.
The above is the detailed content of Simplified Stream Response Handling in Laravel. For more information, please follow other related articles on the PHP Chinese website!