How to Get List Files in Laravel Directory

Sovary September 29, 2022 624
1 minute read

We would like to show how to get list all files in folder Laravel directory. We will give example to show about Laravel get all files in directory. We also can use this in Laravel 6 Laravel 7 Laravel 9.

There are different ways get all files in directory using Laravel or PHP code. We will show how to get list of files in current directories and getting list of all files in current and sub-directories. Please look at examples of code below to getting all files list and we will use Laravel storage and facade Laravel to get the files.

Getting List Files in Current Directory

For example we have a folder contain many files and we want to see list all files exist in current directory, we should use as below code

Create File app -> Http -> Controllers -> TestController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
  
class TestController extends Controller
{
    public function index()
    {
        $directory = "uploads";
        $files = Storage::files($directory);
  
        dd($files);
    }
}

Output:

Array
(
    [0] => uploads/android.pdf
    [1] => uploads/placeholer.jpeg
    [2] => uploads/landscape.png
)

Get All Files include All Sub-Directories

For example, in a folder there are many files inside include sub-folder there are also contain files as well. How to get those files?

Create File app -> Http -> Controllers -> TestController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
  
class TestController extends Controller
{
    public function index(Request $request)
    {
        $dir = "uploads";
        $files = Storage::allFiles($dir);
        dd($files);
    }
}

Output:

Array
(
    [0] => uploads/error.txt
    [1] => uploads/images/912c120d12e02.png
    [2] => uploads/images/15812b3c3f1a.jpeg
    [3] => uploads/doc/report.pdf
)

Thanks for reading my article, hope this short tutorial would help you.

You migth also like...

 

Laravel  PHP  Laravel 9 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him