We may sometime require to download zip or pdf file for report or invoice in Laravel 5 application. So in this article i will let you know how to force download file using response "download()" method.
As we know, we have to make response from controller for download file. So you have to simple return response with download().
download() take three argument as listed bellow syntax:
Syntax Download Method:
return response()->download($pathToFile, $name, $headers);
1) $pathToFile: path of force download file.
2) $name: assign new name of force download file.
3) $headers: set headers fop force download file.
As you see above syntax, you can just understand how to use download(), So here i will give you simple and basic example of download method.
Add Route
routes/web.php
Route::get('forceDonwload', 'HomeController@forceDonwload');
Add Controller Method
app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function forceDonwload()
{
$pathToFile = public_path("myReportFile.pdf");
$name = time().'.pdf';
$headers = ['Content-Type: application/pdf'];
return response()->download($pathToFile, $name, $headers);
}
}
Make sure you have "myReportFile.pdf" file on your public directory for example.
As above simple example, you can run quick and check how it easy.
I hope you found best solution...
Do you like below Tutorials ?
- Laravel 5.6 - Collection could not be converted to int
- Laravel - How to generate secure https URL from route?
- Laravel - Vue JS File Upload Example
- How to get last 7 days data in Laravel?
- Laravel Validation required if other field empty example
- Laravel Eloquent - When Case Statement in Select Query Example
- Laravel 7.x and 6.x Passing Variable to Javascript Example
- How to pass PHP variables in JavaScript or jQuery?