Search code examples
phplaravel-8laravel-livewire

Delete the row after removing file from storage


everything works perfectly but it throw an error “Trying to get property ‘path’ of non-object” on this line “unlink(“uploads/”.$img->path);” and when I refresh the row and file are deleted .if there is another way please tell me

blade :

<table class="table table-hover">

  <thead>

    <tr>

     <th scope="col">image</th>
     <th scope="col">title</th>
     <th scope="col">Actions </th>
     </tr>

     </thead>



        <tbody>

  @foreach($data as $img)

<tr>

<th scope="row"> <img src="uploads/{{ $img->path }}" width="50%" /></th>

  <td>{{$img->title}}</td>
   <td>

  <a href='#'><i class="fa fa-edit"    id="updateIcon"   wire:click="selectItem({{ $img->id }}, 'update')" ></i></a>

  &nbsp;&nbsp;

  <a href="#"><i class="fa fa-trash" style='color:red;'    wire:click="selectItem({{ $img->id }}, 'delete')"  data-target="#modalFormDelete"></i></a>

  </td>

    @endforeach

</tr>



       
class:
   public function selectItem($itemId, $action)
    {
        $this->selectedItem = $itemId;
        if ($action == 'delete') {
             $this->dispatchBrowserEvent('openDeleteModal');
        }
        
        
    }
    public function delete()
    {
        $img=Caroussel_Img::find($this->selectedItem);
        unlink("uploads/".$img->path);//bug here
        Caroussel_Img::where("id",$img->id)->delete();
        $this->dispatchBrowserEvent('closeDeleteModal');
     }

Solution

  • It is not a good idea, and I don't know what is inside "Caroussel_Img"

    But if it is removing the file add "@" at beginning of the line and it won't bother you anymore

    @unlink("uploads/".$img->path);