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()
.
For this example, define a simple route to download file from controller.
routes/web.phpRoute::get('force-donwload-file', 'HomeController@forceDownloadFile');Home Controller
Now add following code in your HomeController.php
app/Http/Controllers/HomeController.php
- <?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);
- }
- }