简体   繁体   中英

laravel livewire image form

I have form submit function which is working just fine in normal controller but since I've moved my function to livewire component it returns error

Error

ErrorException
Undefined index: attachment 

Code

Error line commented

$chat = new BidChat;
// other fields
if ($this->attachment) {
    $attachment = $this->attachment;
    $filename = 'chat-attachment' . '-' . time() . '.' . $attachment->getClientOriginalExtension();
    $location = public_path('images/' . $filename);


    $valid_images = ['image/jpeg','image/gif','image/png'];
    if(in_array($_FILES['attachment']['type'], $valid_images)){ <-- error comes from this line
        Image::make($attachment)->resize(1300, 362)->save($location);
    }

    $chat->attachment = $filename;
}
$chat->save();

Debug

Result of dd($this->attachment);

Livewire\TemporaryUploadedFile {#1559 ▼
  +"disk": "local"
  #storage: Illuminate\Filesystem\FilesystemAdapter {#1538 ▶}
  #path: "livewire-tmp/najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  -test: false
  -originalName: "najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  -mimeType: "application/octet-stream"
  -error: 0
  #hashName: null
  path: "C:\Users\root\AppData\Local\Temp"
  filename: "najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  basename: "phpBAD0.tmp"
  pathname: "C:\Users\root\AppData\Local\Temp\phpBAD0.tmp"
  extension: "tmp"
  realPath: "C:\laragon\www\mysite\storage\app\livewire-tmp/najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  size: 15036
  writable: false
  readable: false
  executable: false
  file: false
  dir: false
  link: false
}

HTML

<form wire:submit.prevent="submit" enctype="multipart/form-data" method="post">
  @csrf
  <input type="file" wire:model="attachment" class="form-control" />

  <button class="button btn-block">Save</button>
</form>

Any idea?

Update

It seems to be known issue

in livewire you can't $_FILES['attachment']['type'] access this data for validation you can do like this

$chat = new BidChat;
// other fields
if ($this->attachment) {
    $attachment = $this->attachment;
    $filename = 'chat-attachment' . '-' . time() . '.' . $attachment->getClientOriginalExtension();
    $location = public_path('images/' . $filename);

    $this->validate([
        'attachment' => 'image|mimes:jpeg,png,jpg,gif',
    ]);

    Image::make($attachment)->resize(1300, 362)->save($location);
    $chat->attachment = $filename;
}
$chat->save();

ref link https://laravel-livewire.com/docs/2.x/file-uploads

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM