In Laravel, how can I obtain a list of all files in a public folder?

kant312 picture kant312 · Jul 9, 2015 · Viewed 66.4k times · Source

I'd like to automatically generate a list of all images in my public folder, but I cannot seem to find any object that could help me do this.

The Storage class seems like a good candidate for the job, but it only allows me to search files within the storage folder, which is outside the public folder.

Answer

igs013 picture igs013 · Jul 9, 2015

You could create another disk for Storage class. This would be the best solution for you in my opinion.

In config/filesystems.php in the disks array add your desired folder. The public folder in this case.

    'disks' => [

    'local' => [
        'driver' => 'local',
        'root'   => storage_path().'/app',
    ],

    'public' => [
        'driver' => 'local',
        'root'   => public_path(),
    ],

    's3' => '....'

Then you can use Storage class to work within your public folder in the following way:

$exists = Storage::disk('public')->exists('file.jpg');

The $exists variable will tell you if file.jpg exists inside the public folder because the Storage disk 'public' points to public folder of project.

You can use all the Storage methods from documentation, with your custom disk. Just add the disk('public') part.

 Storage::disk('public')-> // any method you want from 

http://laravel.com/docs/5.0/filesystem#basic-usage

Later Edit:

People complained that my answer is not giving the exact method to list the files, but my intention was never to drop a line of code that the op copy / paste into his project. I wanted to "teach" him, if I can use that word, how to use the laravel Storage, rather then just pasting some code.

Anyway, the actual methods for listing the files are:

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

// Recursive...
$files = Storage::disk('public')->allFiles($directory);

And the configuration part and background are above, in my original answer.