Skip to content

How to force download files in Laravel?

Last updated on February 17, 2018

Giving download option to the user is a pretty common requirement in today’s web apps for the variety of reasons. For example, if your application is related to online shopping, you might need an invoice download feature, in this scenario, you might need to force the user’s browser to download the file at the given path.

Here I am gonna show you, How easy it is to force the browser to download user requested file instead of showing in the browser in your Laravel based application. force download files laravel

Laravel Response class has a method called download() and we gonna use this method to handle downloads. The download method accepts a file path as the first argument and file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

For example, define a simple route as shown below.

Route::get('file-download', 'FileDownloadController@index');

Create a controller called FileDownloadController with bellow command –

php artisan make:controller FileDownloadController

After generating controller add index method to it following code.

download($file, $name);
    }
}

In the above code example, the file is located in storage/app directory, you can place files wherever you want to, make sure to update the correct file path.

Now start the app with php artisan serve and head over to the browser with http://localhost:8000/file-download you will get file download promte.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments