In this guide, I will show you how to implement file downloading in Laravel 11 using Livewire 3. Livewire makes it easy to trigger file downloads without requiring complex JavaScript. Whether you need to download PDFs, images, or other files, this guide will help you set it up step by step.
Step-by-Step Guide to File Downloading in Laravel 11 with Livewire 3
If Laravel 11 is not already installed, I install it using:
composer create-project laravel/laravel livewire-file-download
cd livewire-file-download
Next, I install Livewire 3:
composer require livewire/livewire
I generate a Livewire component for handling file downloads:
php artisan make:livewire FileDownload
This creates two files:
app/Livewire/FileDownload.php
(Component class)resources/views/livewire/file-download.blade.php
(Component view)I open app/Livewire/FileDownload.php
and update it:
namespace App\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class FileDownload extends Component
{
public function downloadFile()
{
$filePath = 'downloads/sample.pdf'; // Change to your file path
if (!Storage::disk('public')->exists($filePath)) {
session()->flash('error', 'File not found!');
return;
}
return Storage::disk('public')->download($filePath);
}
public function render()
{
return view('livewire.file-download');
}
}
I open resources/views/livewire/file-download.blade.php
and add a button for downloading files:
<div>
@if (session()->has('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
<button wire:click="downloadFile" class="btn btn-primary">Download File</button>
</div>
I make sure a sample file exists in storage/app/public/downloads/sample.pdf
. If it doesn’t exist, I create it and move it to this directory.
To make sure the public
storage is accessible, I run:
php artisan storage:link
I include the Livewire component inside resources/views/welcome.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel Livewire File Download</title>
@livewireStyles
</head>
<body>
<div class="container">
<h1>Laravel 11 Livewire 3 File Download</h1>
<livewire:file-download />
</div>
@livewireScripts
</body>
</html>
Finally, I start the Laravel development server:
php artisan serve
You might also like:
In this article, we will explore how to implement a file upload feature in Angular 15 with a progress bar. We will guide...
Jun-23-2023
In this article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...
Jan-04-2021
In this post we will see Laravel 8 qr code generate example. we will generate QR Code using simple-qrcode package....
Jun-30-2021
Hello developers! In this article, we'll learn about Laravel 11 to create Creat Reas Update Delete operations w...
Apr-08-2024