Posts Learn Components Snippets Categories Tags Tools About
/

How to Get All Files Within a Directory in Laravel

Learn how to retrieve files within a directory in Laravel using the Storage facade. Make use of this method to get meaningful information of the filename and path.

Created on Sep 01, 2021

1105 views

To get all of the files within a directory you can make use of the "files()" method available from the "Storage" facade. Running the code below will return an array of the files within the directory you have specified.
<?php

$files = Storage::files($directory);
If within the directory there are subdirectories then it will be listed as a directory, to get all of the files within the subdirectory you can call the "allFiles()" method.
<?php

$files = Storage::allFiles($directory);
Do note that it supports listing nested directories.
<?php

Storage::allFiles('path/to/directory/);

How to specify Disk instance used?


Since some Laravel applications will have multiple disks, you can specify the disk to use like below.
<?php

Storage::disk('s3')->allFiles('path/to/directory/); // if you are useing 's3' disk
Storage::disk('public')->allFiles('path/to/directory/); // if you are using 'public' disk
Do note that by default it will be using the one specified within the .env file like below.
# .env
FILESYSTEM_DRIVER=local

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)