简体   繁体   中英

Delete All Files Except 'placeholder.png' in folder using Laravel

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

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.

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