Skip to content

Posts › Development

Development

Laravel: Rendering view as file donwload

More than once I needed to render a laravel view as a downlodable file. This task could be easily accomplished

1 min read
Laravel: Rendering view as file donwload

More than once I needed to render a laravel view as a downlodable file. This task could be easily accomplished as follows:

Inside your controller:

php
 1    public function action(Request $request)
 2    {
 3        $data_to_pass = ['a' => 'test'];
 4        return response(view('view_name')->with(compact('data_to_pass')), 200, [
 5            'Content-Type' => 'application/xml', // use your required mime type
 6            'Content-Disposition' => 'attachment; filename="filename.xml"',
 7        ]);
 8    }

where:

view_name is the name of the blade view to render.
data_to_pass is/are the name/s of one or more variable to pass to the view.
Content-type is the mime type of the file to return, e.g. xml, json, txt...
Content-disposition is the way data are returned to the browser, for download, attachment is required. filename defines the name to use for the downloaded file.