Laravel 5 force download file with the response helper method

Laravel 5 force download file with the response helper method

In this Laravel tutorial, I will tell you about the download() method that is used to generate a response to force download the file in Laravel application.

Sometime, You need to download the report or invoices from the controller then you can use this download() method to download files directly.

The download method accept the three arguments.

In first argument, You will pass the path of download file and the second argument will hold the file name, Finally the third argument hold the HTTP headers. You can change the filename of download file by passing it as a second argument in download().

Routes

For this example, define a simple route to download file from controller.

routes/web.php
Route::get('force-donwload-file', 'HomeController@forceDownloadFile');
Home Controller

Now add following code in your HomeController.php

app/Http/Controllers/HomeController.php

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. class HomeController extends Controller
  5. {
  6. public function forceDownloadFile()
  7. {
  8.     $filePath = public_path("my_invoice.pdf");
  9.     $headers = ['Content-Type: application/pdf'];
  10.     $fileName = time().'.pdf';
  11.     return response()->download($filePath, $fileName, $headers);
  12. }
  13. }

Phone: (+91) 8800417876
Noida, 201301