How to upload images using Laravel Livewire and Spatie media library?

Viewed 2953

I am using Laravel Livewire and Spatie media library and I couldn't find anything helpful on both of their documentation on how to do this.

am trying this but it gave me error

$this->menu->addMediaFromUrl($this->menu_image->temporaryUrl())->toMediaCollection('menu_image');

am getting this error error am getting

4 Answers

For me it works like this:

public $uploadedItems;
    
public function updatedUploadedItems($uploadedFile)
{
    $item = Item::create();

    $item
        ->addMedia($uploadedFile->getRealPath())
        ->usingName($uploadedFile->getClientOriginalName())
        ->toMediaCollection('images');
}

Since my storage and temporary folder are both on s3, the answers did not work for me.
Here's one that worked for me

use Spatie\MediaLibrary\Support\RemoteFile;

...

return $gallery->addMedia($photo->getRealPath())
            ->setFile(new RemoteFile($photo->getRealPath(), 's3'))
            ->usingName($photo->getClientOriginalName())
            ->toMediaCollectionOnCloudDisk('default');

This is the only way it worked for me after testing

      $this->menu
           ->addMediaFromString($this->menu_image->get())
           ->usingFileName($this->menu_image->getFilename())
           ->toMediaCollection('menu_image');

I've tried all the above options but none seems to work for me so i dug deeper and this is the solution working for me. It's more like a hack but it worked for me.

$this->lecture
      ->addMediaFromDisk('livewire-tmp/'.$this->lectureVideo->getFilename())
      ->toMediaCollection();

Maybe it has to do with working environment but getRealPath() throws file not not found exception.

Related