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
Attention Required! | Cloudflare

Sorry, you have been blocked

You are unable to access ressim.net

Why have I been blocked?

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.