Home > Software design >  Laravel, Downloading file directly from route set in menu item
Laravel, Downloading file directly from route set in menu item

Time:11-09

I have a menu being built from an array and I'm making one of the menu items link straight to a download from local storage. The menu item is being built here:

['name' => 'Download Now', 'route' => 'file.download.test'],

And here's the route I'm hitting:

Route::group(['prefix' => 'download'], function () {

    Route::get('test', 'file\downloadController@testingDownload')
        ->name('file.download.test');
});

I'm confused on the controller function though. The file needed to be downloaded is in the local disk in a folder called 'test_downloads' so /storage/test_downloads is the path. I only ever have one file in that folder, but do I need to send the explicit file name through the route? I just want clicking on the menu item to trigger the download of the file, called 'Test_file.xslx'

public function testingDownload(){
    $file = Storage::disk('local')->get($file_name);
    $filepath = storage_path("test_downloads/{$data->file}");
    
    return \Response::download($filepath);
}

CodePudding user response:

In testingDownload() it appears that you are using the variables $file_name and $data; they will be undefined as they have not been set.

You do not require passing the file name through the route if you don't need the filename to be "variable", as you're using a static filename, perhaps this is better suited?

public function testingDownload(){
    // Set the static file name you want to download
    $file_name = 'Test_file.xslx';

    // Using the given file_name, get the file from our configured storage path
    $file = storage_path("test_downloads/{$file_name}");

    // Send a download response with the file
    return \Response::download($file);
}
  • Related