Skip to content

Instantly share code, notes, and snippets.

@nkeena
Last active January 19, 2023 19:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nkeena/c79c2ad461272238e704074cb311cb07 to your computer and use it in GitHub Desktop.
Save nkeena/c79c2ad461272238e704074cb311cb07 to your computer and use it in GitHub Desktop.
Download a file using Laravel Livewire
<div>
<button wire:click="download">Download</button>
</div>
// include this script block after the livewire scripts
<script>
window.livewire.on('startDownload', path => {
// open the download in a new tab/window to
// prevent livewire component from freezing
window.open('download/' + path, '_blank');
});
</script>
<?php
use Livewire\Component;
class Download extends Component
{
public function download()
{
// get the path to the file
$path = "";
// emit an event with the path
$this->emit('startDownload', $path);
}
public function render()
{
return view('download');
}
}
<?php
Route::get('download/{path}', function($path) {
return Illuminate\Support\Facades\Storage::download($path);
})->where('path', '.*');
@Elshaden
Copy link

Elshaden commented Dec 2, 2022

This is a bit Late, but came across this gist, and thought why all the fuss.
Much Simpler way in one method

           $url = $path ;// or any external url
           $headers = ['Content-Type: application/pdf'];
            return response()->streamDownload(function () use ($url) {
                echo file_get_contents($url);
            },'somefilename.pdf', $headers);

@Kepsondiaz
Copy link

you can also use :
return response()->download(public_path(' path file you want download'));
or
return response()->download(storage_path(' path file you want download'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment