Download a file in Laravel using a URL to external resource

There's no magic, you should download external image using copy() function, then send it to user in the response:

$filename = 'temp-image.jpg';
$tempImage = tempnam(sys_get_temp_dir(), $filename);
copy('https://my-cdn.com/files/image.jpg', $tempImage);

return response()->download($tempImage, $filename);

TL;DR
Use the streamDownload response if you're using 5.6 or greater. Otherwise implement the function below.

Original Answer
Very similar to the "download" response, Laravel has a "stream" response which can be used to do this. Looking at the API, both of the these functions are wrappers around Symfony's BinaryFileResponse and StreamedResponse classes. In the Symfony docs they have good examples of how to create a StreamedResponse

Below is my implementation using Laravel:

<?php

use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

Route::get('/', function () {
    $response = response()->stream(function () {
        echo file_get_contents('http://google.co.uk');
    });

    $name = 'index.html';

    $disposition = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        $name,
        str_replace('%', '', Str::ascii($name))
    );

    $response->headers->set('Content-Disposition', $disposition);

    return $response;
});

Update 2018-01-17

This has now been merged into Laravel 5.6 and has been added to the 5.6 docs. The streamDownload response can be called like this:

<?php

Route::get('/', function () {
    return response()->streamDownload(function () {
        echo file_get_contents('https://my.remote.com/file/store-12345.jpg');
    }, 'nice-name.jpg');
});

Tags:

Php

Laravel