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 ?
- React JS Http Post Request Example
- React JS Http Delete Request Example
- Angular 9 Multi Select Dropdown Example
- How to Use Multi Select Dropdown in Angular?
- Laravel Install and Use Ckeditor Example
- Laravel Summernote Editor Example Tutorial
- Laravel Bootstrap Wysihtml5 Editor Example
- Multidimensional Array Search By Value in PHP