Last active
January 19, 2023 19:23
-
-
Save nkeena/c79c2ad461272238e704074cb311cb07 to your computer and use it in GitHub Desktop.
Download a file using Laravel Livewire
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div> | |
<button wire:click="download">Download</button> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Route::get('download/{path}', function($path) { | |
return Illuminate\Support\Facades\Storage::download($path); | |
})->where('path', '.*'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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'));