'Delete wildcard files with Storage facade in Laravel

Is there a way which allows you to delete files with a wildcard through the Storage facade in Laravel?

use Illuminate\Support\Facades\Storage;

Storage::disk('foo')->delete('path/TO_DELETE*');

I may have a list like this

path/TO_DELETE_1
path/TO_DELETE_2
path/TO_KEEP_1
path/TO_PROCESS_1

But I want to delete only the files. I want to avoid path manipulation as much as possible



Solution 1:[1]

Suppose if you have files start with a_1.jpg,a_2.jpg then

 $files = Storage::disk("public")->allFiles();

        foreach ($files as $file){

            if(Str::startsWith($file,"a_")){

                Storage::disk('images')->delete($file);
            }

        }

or for multiple folder search

$directories = Storage::disk('public')->directories();

    foreach ($directories as $directory){
        $files=    Storage::disk('public')->allFiles($directory);

        foreach ($files as $file){
          
            if(Str::startsWith($file,$directory."/"."a_")){
                
                  Storage::disk('public')->delete($file);
            }

        }
    }

Another way is using File facade.

File::delete(File::glob(storage_path('app/public/*/a_*.*')));

For example you have multiple folders inside storage/app/pubic/ then you can specify like this.

app/public/*/a_*.*' 

Here

  1. First * is any folder inside public folder.

  2. a_* means any file start from a_.

  3. .* is any extension.

For last one i took help from this post Ref:Delete files with wildcard in Laravel

Solution 2:[2]

The sub question here is how to get a list of filtered files in Laravel. This works pretty well:

$fileFilter = "someStringFilenameContains";
$files = collect($fileSource->files())->filter(function ($value) {
       return str_contains($value, $fileFilter);
})->toArray();

You can modify str_contains (strstr(), substr() for instance) to suit your needs - anything that returns a truth value really.

This will give you an array of filenames that match your $fileFilter

then to answer the OP:

$fileSource->delete($files);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ChronoFish