Laravel 7.x and 6.x - Force Download File using response helper

November 6, 2017 | Category : Laravel 5.5 Laravel 5 Laravel PHP

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...