Laravel 8 Download File Example


Share:
Published By: Admin, Published On: Jul 21, 2021, Category: Laravel 8 Laravel

Hi Dev

Today,In this tutorial I will share something you how to download file in laravel 8. i will show example of response download with file in laravel 8.We need 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, first of all i will pass First argument of download() I have to give path of download file. We can rename of download file by passing second argument of download(). We can also set headers of file by passing third argument.

First i am going to create new route for our example as like bellow:

Here, i will give you full example of how to download file in laravel so basically follow my all steps.

Path : routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileDownloadController;

/*
|--------------------------------------------------------------------------
| 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', [FileDownloadController::class, 'index'])->name('file.download.index');

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

Path : app\Http\Controllers\FileDownloadController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

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

It will help you...

Share: