Get all file list from directory and sub directory in laravel

In this example, we will get a list of all files from the directory in Laravel using the Storage Facade. It’s focused on how to get all files in a directory Laravel. I would like to show you that Laravel gets all files in the directory. In PHP or Laravel there are many ways to get a list of all files but in this example, we will use a storage facade.

Let’s see some examples to get a file list from directories and sub-directories.

The files() function of the storage facade returns all files from a directory. It takes the directory name as input and returns an array of files.

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;

class TestController extends Controller
{
    public function index(){
        $directory = "public";
        $files = Storage::files($directory);

        dd($files);
    }
}

Output:

array:4 [
  0 => "public/.gitignore"
  1 => "public/file1.txt"
  2 => "public/file2.txt"
  3 => "public/file3.txt"
]

As you can see in the above example, there are few files in the public directory of the storage folder. So we call the files method of Storage facade it will return all files from a directory.

If you need to access all files including from the sub-directory then you can use the allFiles() function. This function will return the full path from that directory from a sub-folder or sub-directory.

In the below example, we will get all files from the sub-directory too:

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;

class TestController extends Controller
{
    public function index(){
        $directory = "public";
        $files = Storage::allFiles($directory);

        dd($files);
    }
}

Output:

array:4 [
  0 => "public/.gitignore"
  1 => "public/file1.txt"
  2 => "public/file2.txt"
  3 => "public/file3.txt"
  4 => "public/dir1/file3.txt"
  5 => "public/dir2/file3.txt"
]

Conclusion

Here, we have taken two examples that will return a list of files from a specific directory to the user. While working with files those methods can easily be used in Laravel as compared to PHP. You can use the return of function as per your requirement.