How to show all files from directory in laravel?

Member

by domenico , in category: PHP CMS , 8 months ago

How to show all files from directory in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 8 months ago

@domenico 

To show all files from a directory in Laravel, you can use the Storage facade provided by Laravel. Here is a step-by-step guide to achieve this:

  1. Add the following use statement at the top of your controller:
1
use IlluminateSupportFacadesStorage;


  1. Use the files method provided by the Storage facade to get an array of all files in a directory. Pass the directory path as an argument to the files method. For example, to get all files from the public/images directory, you can use the following code:
1
$files = Storage::files('public/images');


  1. Loop through the $files array and display the file names. For example, you can use a foreach loop to iterate over the files and show them in a view:
1
2
3
foreach ($files as $file) {
    echo $file. "<br>";
}


  1. You can also use the allFiles method instead of files to get all files including files from all subdirectories within a directory.
1
$files = Storage::allFiles('public/images');


Make sure to update the directory path according to your project's directory structure. This way, you can easily show all files from a directory in Laravel.