Fariza
Fariza

Reputation: 33

How to unlink multiple files in Laravel

I want to unlink all file with name from the database: file name in database. I try to use code like this but it doesn't work:

public function destroy($id)
{
     $infokeg = Infokeg::where('id', $id)->first();
     $image[] = $infokeg->foto_kegiatan
     unlink(public_path("data_file/".json_decode($image)));
     $infokeg->delete();
     return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
}

Upvotes: 2

Views: 999

Answers (2)

Fariza
Fariza

Reputation: 33

using for to delete it

public function destroy($id)
    {
       $infokeg = Infokeg::where('id', $id)->first();
       $image = json_decode($infokeg->foto_kegiatan);
       $length = count($image);
       for ($i = 0; $i < $length; $i++) {
           unlink(public_path("data_file/".$image[$i]));
       }
       $infokeg->delete();
       return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
   }

Upvotes: 0

bhucho
bhucho

Reputation: 3420

File::delete() will handle the array of files to be deleted for you,

At first, add it use Illuminate\Support\Facades\File;

public function destroy($id)
{
 $infokeg = Infokeg::where('id', $id)->first();
 $image[] = $infokeg->foto_kegiatan  
 // pass the array of files to deleted to it. 
 // if $image array is like this $image = ['file1.jpg', 'file2.png'];
 File::delete($image);
 
 return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
}

Method 2

At first add use Illuminate\Support\Facades\Storage;

public function destroy($id)
{
 $infokeg = Infokeg::where('id', $id)->first();
 $image[] = $infokeg->foto_kegiatan  
 // pass the array of files to deleted to it. 
 // if $image array is like this $image = ['file.jpg', 'file2.jpg'];
 Storage::delete($image);
 
 return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
}

For method 2 refer from docs


EDIT:

append public path to all,

foreach ($image as &$value) {
   $value = public_path("data_file/".$value);
}

It will append the public path to all the values in the array, then use it in the delete() method as its argument.

Upvotes: 2

Related Questions