When working with files in Laravel, it’s often necessary to get file list from directory in Laravel to manage or display them efficiently. Using the Storage Facade, we can easily retrieve all files from a directory or sub-directories. While PHP offers multiple methods to list files, Laravel’s built-in approach simplifies the process and keeps the code clean.
Let’s explore examples to fetch file lists from directories and sub-directories in Laravel.
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.
Here we explored how to get file lists in Laravel, but when working with core PHP, you may also need to check file exists or not using PHP before performing file operations.