meeshka
2 years ago
2164
13
Laravel

Dynamic content for download (Content-Disposition the laravel way...)

Posted 2 years ago by meeshka

Hi,

I am working on a CSV download feature for a project. I finally got it working with the following (relies directly on Symfony Components (http://symfony.com/doc/current/components/http_foundation.html#serving-files)). When I tried replacing $response = new Response($fileContent); with $response = response() it didn't work. Without, that it works fine within a controller method. I'm trying to make/keep it as Laravel as possible without requiring to import Symfony components directly.

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$fileContent = ...; // the generated file content
$response = new Response($fileContent);

$disposition = $response->headers->makeDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'foo.pdf'
);

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

Please sign in or create an account to participate in this conversation.