How to job file upload with Livewire?

2k views Asked by At

I need to upload file to S3 by queue the image then upload to S3 using Livewire

My livewire Component :

class s3 extends Component
{
    use WithFileUploads;

    public $image;

    public function save()
    {
        $this->validate(['image' => 'image']);

        dispatch(new ImageUpload($this->image));

        return 'success';
    }
}

MY job class for queue working:

class ImageUpload implements ShouldQueue
{
    
    public $image;

    public function __construct($image)
    {
        $this->image = $image;
    }

    public function handle()
    {
        Storage::disk('s3')->put('uploads/product_images/', $this->image, 'public');
    }
}

I got this error::

Exception
Serialization of 'Livewire\TemporaryUploadedFile' is not allowed
1

There are 1 answers

2
Giovanni S On BEST ANSWER

You will have to pass something that can be serialized.

One way off the top of my head (since it looks like you are storing the temporary file) would be to simply pass the temporary filename and path to your job which will handle the rest.

Something like this should work:

Your Livewire component:

class s3 extends Component
{
    use WithFileUploads;

    public $image;

    public function save()
    {
        $this->validate(['image' => 'image']);

        $image = [
            'name' => $this->image->getClientOriginalName(),
            'path' => $this->image->getRealPath(),
        ];

        dispatch(new ImageUpload($image));

        return 'success';
    }
}

Your Job class:

class ImageUpload implements ShouldQueue
{
    
    public $image;

    public function __construct($image)
    {
        $this->image = $image;
    }

    public function handle()
    {
        Storage::disk('s3')->put('uploads/product_images/'.$this->image['name'], file_get_contents($this->image['path']), 'public');
    }
}

It's crude but should get you in the right direction.