1

So I'm trying to figure this all out here. I've seen this post below about how to delete all files within a directory, however I want to exclude my placeholder image from this deletion. I haven't come across the answer I'm looking for yet on SO, so this is just going to be a short and simple question.

Take a look at this SO question here: Laravel File Storage delete all files in directory

J. Robinson
  • 931
  • 4
  • 17
  • 45
  • you can apply check if placeholder.png exist in directory then except that delete all, you just have to make your placeholder image unique name. – Vipertecpro Aug 21 '18 at 11:01

1 Answers1

3

delete() accepts an array of files for deletion. Thus, one possible solution is listing the directory with a wildcard selector, then filter out your exclusion list from the array.

$filesForDelete = array_filter(glob("path/to/files/*"), function($file) {
    return false === strpos($file, 'placeholder.png');
});

Storage::delete($filesForDelete);

Of course, your filter expression may become better, broader, or just do the same thing in many other ways.

For example, you may create a helper function like this:

function deleteAllButFile($exclude)
{
    $filesForDelete = array_filter(glob("path/to/files/*"), function($file) use ($exclude) {
        return false === strpos($file, $exclude);
    });
    Storage::delete($filesForDelete);
}

// Call it like
deleteAllButFile('placeholder.png');

Or any other way you like. Up to your imagination.

alariva
  • 2,051
  • 1
  • 22
  • 37
  • Will try this tomorrow after I get off work. If I can implement it successfully you'll definitely get the answer and an upvote from me! Thank you for taking the time! – J. Robinson Aug 21 '18 at 03:12
  • Also maybe you could help with this question as well: https://stackoverflow.com/questions/51940859/laravel-faker-image-save-to-multiple-directories-with-same-filename – J. Robinson Aug 21 '18 at 03:12