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
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.phpapp/Http/Controllers/HomeController.php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- class HomeController extends Controller
- public function forceDownloadFile()
- $filePath = public_path("my_invoice.pdf");
- $headers = ['Content-Type: application/pdf'];
- $fileName = time().'.pdf';
- return response()->download($filePath, $fileName, $headers);