🔥 Download the Response of an HTTP Request in Laravel
Published on by Paul Redmond
Marcel Pociot shared a tip on using the Laravel HTTP client method sink() to write a response to a file:
I just learned about a neat little undocumented @laravelphp HTTP client method.— Marcel Pociot 🧪 (@marcelpociot) June 20, 2023
The "sink" method allows you to pass a filename or resource. The response to the request will then be written to this file.
This makes it super easy to download remote files with additional headers pic.twitter.com/ZHHURltcfA
The sink request option is also available in the Guzzle HTTP client library, formerly the
save_to request option:
$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);// PHP stream$resource = \GuzzleHttp\Psr7\Utils::tryFopen('/path/to/file', 'w');$stream = \GuzzleHttp\Psr7\Utils::streamFor($resource);$client->request('GET', '/stream/20', ['sink' => $stream]);
If you'd like to learn more about all the excellent features Laravel's HTTP request class provides, check out the HTTP Requests documentation. The PendingRequest source is another excellent resource to see how Laravel's HTTP client works under the hood.