I will explain step by step tutorial laravel livewire file upload. you can see laravel livewire file upload example. we will help you to give example of file upload with laravel livewire. We will use laravel livewire store upload file.
In this tutorial, we will create a simple image/file upload example using laravel livewire. We can use this laravel livewire image upload source code with laravel 6, laravel 7, laravel 8 and laravel 9 version. You know that Livewire makes uploading and storing files extremely easy.
If we want to upload a file, image, or any media with laravel, then we have to use the WithFileUploads trait in the livewire component. Here, I will give you a very simple example of creating a file upload form with a title and name and I will store that data in the database without refreshing the page and with too many lines of code in the blade file. we will use only the livewire/livewire
package.
So, let's follow the bellow step and you will get bellow layout:
App\Http\Livewire\DemoComponent.php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
class ComposeEmail extends Component
{
use WithFileUploads;
public $file;
public function save()
{
$this->validate([
'file' => 'image|max:1024', // 1MB Max
]);
if($this->file) {
$this->file->store('attachment');
//this will upload the photo in storage attachment directory
$this->file->store('attachment','public); //push it to public
}
}
}
All are set to go for the server, now we have to create an image upload form for laravel livewire.
We can upload images in laravel with livewire like:
// Store the uploaded file in the "photos" directory of the default filesystem disk.
$this->photo->store('photos');
// Store in the "photos" directory in a configured "s3" bucket.
$this->photo->store('photos', 's3');
// Store in the "photos" directory with the filename "avatar.png".
$this->photo->storeAs('photos', 'avatar');
// Store in the "photos" directory in a configured "s3" bucket with the filename "avatar.png".
$this->photo->storeAs('photos', 'avatar', 's3');
// Store in the "photos" directory, with "public" visibility in a configured "s3" bucket.
$this->photo->storePublicly('photos', 's3');
// Store in the "photos" directory, with the name "avatar.png", with "public" visibility in a configured "s3" bucket.
$this->photo->storePubliclyAs('photos', 'avatar', 's3');
Read also: How to Install CKEditor in Laravel Livewire
Hope it can help you.
#laravel #laravel-9x #livewire