How To Download File Example In Laravel 8?

Dec 18, 2021 . Admin



Hi Dev,

This example is how to download file example in laravel 8?.

We will show example of response download with file in laravel 8.

We can rename of download file by passing second argument of download().

In this blog, First argument of download() I have to give path of download file. We can also set headers of file by passing third argument.

Today,I will learn you how to download file in laravel 8. We sometimes require to return response with download file from controller method like generate invoice and give to download or etc. Laravel 8 provide us response() with download method that way we can do it.

So let's start following example.

routes/web.php

use App\Http\Controllers\DownloadFileController;
Route::get('/file-download', [DownloadFileController::class, 'index'])->name('file.download.index');

Now,I have to add one method "downloadFile()" in my DownloadFileController. If you don't have DownloadFileController then you can use your own controller as like bellow:

App\Http\Controllers\DownloadFileController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DownloadFileController extends Controller
{
    public function index()
    {
    	$filePath = public_path("dummy.pdf");
    	$headers = ['Content-Type: application/pdf'];
    	$fileName = time().'.pdf';

    	return response()->download($filePath, $fileName, $headers);
    }
}

I hope it will help you....

#Laravel 8