Posted by Arjun on Tuesday 21st November 2017

How to force download files in Laravel?

How to Laravel Laravel 5.x files Download force

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.

[caption id="attachment_5616" align="aligncenter"]force download files laravel force download files laravel[/caption]

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', '[email protected]');

Create a controller called FileDownloadController with bellow command -

php artisan make:controller FileDownloadController

After generating controller add index method to it following code.

<?php
namespace App\Http\Controllers;

class FileDownloadController extends Controller
{
    public function index() {
        $file = '../storage/app/uploads/1.pdf';
        $name = basename($file);
        return response()->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.