Listing files using wildcards with Laravel Storage and AWS S3
Solution 1
Suppose If you want to get all files then you can use this
Storage::disk('s3')->allFiles('');
It will return All file that have in your bucket. but if you want to look particular then
Storage::disk('s3')->allFiles('FolderName');
or
Storage::disk('s3')->allFiles('FolderName/2FolderName');
have a look of this image. when you want to look all files.
Solution 2
$storage = Storage::disk('s3');
$client = $storage->getAdapter()->getClient();
$command = $client->getCommand('ListObjects');
$command['Bucket'] = $storage->getAdapter()->getBucket();
$command['Prefix'] = 'path/to/FS_1054_';
$result = $client->execute($command);
foreach ($result['Contents'] as $file) {
//do something with $file['Key']
}
Solution 3
I have found an answer, though am happy to know if there is a better one.
Use Storage::files(folder_name)
to list all files in the folder, this returns an array. Then use array_where
and starts_with
to filter the list:
$files = Storage::files(folder_name);
$files = array_where($files, function ($value, $key) use ($mask) {
return starts_with(basename($value), $mask);
});
Jonathan Hyams
I have been programming since the early 90s. My main desktop language is Delphi but I do very little of that these days. I am much more into web development using PHP, Javascript and mySQL. I use the Prototype and jQuery libraries too. I have worked extensively in the leisure and cultural industries, developing ticketing applications, inventory systems, and a raft of web sites for art galleries and artists.
Updated on June 30, 2022Comments
-
Jonathan Hyams almost 2 years
I am converting a Laravel (5.3) app to use AWS S3 as image storage. I need to programmatically get list of images whose names comply with a specific mask (eg 'FS_1054_*.JPG') which when I used local storage I could do easily with the glob() function.
Any suggestions as to how I could do this with S3?