Get all file list from directory in laravel

In this example, we will get a list of all files from the directory in Laravel using Storage facade. It's focused on how to get all files in a directory Laravel. I would like to show you Laravel get 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 directory and sub-directories :

The files() function of storage facade returns all files from 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 files method of Storage facade it will return all files from directory.

If you need to access all files including from the sub-directory then you can use allFiles() function. This function will return the full path from that directory from 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 method can easily use in Laravel as compared to PHP. You can use return of function as per your requirement.


Share your thoughts

Ask anything about this examples