Laravel 9 Download File Example

May 10, 2022 . Admin

Hi Dev

Today, In this tutorial I will share something with you about how to download file in laravel 9. I will show an example of a response download with file in laravel 9. We need to return a response with a download file from the controller method like generate the invoice and give to download or etc. Laravel 9 provides us response() with a download method that way we can do it.

So, first of all, I will pass the First argument of download() I have to give the path of the download file. We can rename of download file by passing the second argument of download(). We can also set headers of file by passing third argument.

First I am going to create a new route for our example as like below:

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

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: Create Route 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');
Step 3: Create Controller

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 below:

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

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileDownloadController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $filePath = public_path("demo.pdf");
        $headers = ['Content-Type: application/pdf'];
        $fileName = time().'.pdf';

        return response()->download($filePath, $fileName, $headers);
    }
}
Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/file-download

It will help you...

#Laravel 9