Mikegk's avatar

Delete single item from public Livewire property

Hi guys,

currently I ran into the following problem.

Im Uploading multiple image files via Livewire. After the files have been uploaded, Im emitting / calling a script on the component side that stores the images and generates thumbnails. There is also one array that is filled with the Eloquent Models I get, after storing the images / files (each has its own entry in the images table). So I can simply display thumbnails after the upload has been fulfilled, and a little button which should delete items from the array.

And that's whats not working.

HTML Looks like this

@if(count($images))
    <div>
        @foreach($images as $image)
            @if(isset($image->id))
                <div>
                    <div>
                        <img src="{{url($image->path.$image->name)}}">
                    </div>
                    <div>
                        <button type="button" wire:click="deleteImage({{$image->id}})">Delete</button>
                    </div>
                </div>
            @endif
        @endforeach
    </div>
@endif

And that's the delete function

public function deleteImage($id)
    {
        if(count($this->images)){
            for($i=0;$i<count($this->images);$i++){
                foreach($this->images[$i] as $key => $value){
                    if($key === 'id' && (int)$value === (int)$id){
                        unset($this->images[$i]);
                    }
                }
            }
        }
    }

The problem is, that the complete array will be unset if I click one delete button.

Please have in mind: Im filling an array ($this->images) in a foreach loop with single Eloquent Models. So $this->images is not a collection.

0 likes
1 reply

Please or to participate in this conversation.