How to Response Download File in Laravel ?

Today now in this post i will show you How to Response Download File in Laravel ? Sometimes we may need to return the response with the download file from controller method as like generate invoice and give to the download or etc. In Laravel provide us the response() with the download method on that way we can do this easily.

We can also response the download file from the storage and can delete it after the download in any version laravel 6, laravel 7 and laravel 8 application.

At First argument of download() we need to give the path of download file. We can rename of download file by passing the second argument of download(). So We can also set the headers of file by passing the third argument.

Now in the bellow example it will help you how it is works.

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

routes/web.php

Route::get('donwload-file', 'HomeController@downloadFile');

Ok, now i need to add one the method “downloadFile()” in our HomeController. If we don’t have HomeController then we can use our own controller as like as bellow:

app/Http/Controllers/HomeController.php

Example 1: Download File from Storage
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;

class HomeController extends Controller
{
    public function downloadFile()
    {
    	$myFile = storage_path("folder/dummy_pdf.pdf");
    	return response()->download($myFile);
    }
}
Example 2: Download File with name and headers
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;

class HomeController extends Controller
{


    public function downloadFile()
    {
    	$myFile = public_path("dummy_pdf.pdf");
    	$headers = ['Content-Type: application/pdf'];
    	$newName = 'itsolutionstuff-pdf-file-'.time().'.pdf';
    	return response()->download($myFile, $newName, $headers);
    }
}
Example 3: After Download File will remove
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;

class HomeController extends Controller
{
    public function downloadFile()
    {
    	$myFile = storage_path("folder/dummy_pdf.pdf");


    	return response()->download($myFile)->deleteFileAfterSend(true);
    }
}

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.