Laravel 8 Download File Example

Laravel 8 Download File Example

Hi Dev,

In this blog,I'm able to examine you how to download report in laravel 8. we are able to display instance of reaction download with document in laravel 8.We now and again require to go back reaction with download document from controller technique like generate invoice and deliver to download or and so on.Laravel eight provide us response() with down load approach that way we are able to do it.

Here, First argument of down load() I ought to give route of down load document. we will rename of download record through passing second argument of download(). We can also set headers of file with the aid of passing third argument.

So, first i am going to create new route for our instance as like bellow:

routes/web.php
<?php
use App\Http\Controllers\DownloadFileController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|

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);
    }
}

It will help you...