How to force download files in Laravel?

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.

Create a controller called FileDownloadController with bellow command –

After generating controller add index method to it following code.

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.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments Protection Status
Would love your thoughts, please comment.x