Laravel 9 Download File Example Tutorial

10-Apr-2023

.

Admin

Laravel 9 Download File Example Tutorial

Hi Guys

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

In this blog, the First argument of download() I have to give the path of download file. We can rename the download file bypassing the second argument of download(). We can also set headers of file bypassing the third argument.

Step 1: Download Laravel


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

composer create-project laravel/laravel example-app

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

Step 2: Add Route

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

Step 3: Add Controller

php artisan make:controller DownloadFileController

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DownloadFileController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$filePath = public_path("dummy.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