How To Download File in Laravel 8?

In this short post, I'm sharing how to download files in Laravel 8. If have a project about an online digital shop in which your users can download files after they purchase then this is for you. We are using a download() function from the Laravel 8 Response class to cater the download.

Created on: Sep 01, 2021
6,058
How To Download File in Laravel 8?

In this short post, I'm sharing how to download files in Laravel 8. If have a project like an online digital shop in which users can download files after they purchase then this is for you. We are using a download() function from the Laravel 8 Response class to cater the download.

$filepath = a path for target file to be download

$filename = filename for the downloaded file

$headers = this is an array about the file content type to download

Response::download($filepath, $filename, $headers)

Now you have a basic idea about this function.

We will try to create a route for this.

Route::get('/purchased-download', [\App\Http\Controllers\PurchasedFileController::class, 'download'])->name('purchased.download');

Then let's write our controller, see the complete code below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class PurchasedFileController extends Controller
{
    public function index()
    {
    	$path = public_path('for_pro_members.zip');
    	$fileName = 'purchase_files.zip';

    	return Response::download($path, $fileName, ['Content-Type: application/zip']);
    }
}

I hope it helps. Thank you for reading :)

Leave a Comment