How To Get All Files In A Directory In Laravel?

Sometimes we need to get all the files from a directory. In this tutorial, I will show you how to get all the files from a directory in the Laravel application. This article will give you a clear explanation of getting all files from a directory in Laravel. If you don't know how to get all the files in a directory like a public or storage directory then this example is for you.

This tutorial is made on how to get all files in a directory of Laravel. I wanna show you that Laravel get all files in directory. I will show you a simple about laravel get all file names in the directory. This article goes into detail on laravel list all files in directory. We can use this code in laravel 6, laravel 7, laravel 8 and laravel 9 versions. So, let's see the below example code with output:

Example code: 

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $directory = "public";
        $files = Storage::files($directory);
  
        dd($files);
    }
}

 

Or you can use:

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $directory = "public";
        $files = Storage::allFiles($directory);
  
        dd($files);
    }
}

 

This will return an array of file lists like:

Array
(
    [0] => public/test.pdf
    [1] => public/uploads/test.png
    [2] => public/uploads/test.txt
    [3] => public/uploads/test2.txt
    [4] => public/.gitignore
    [5] => public/test5.pdf
)

 

Read also: How to Update Multiple Records in Laravel 9?

 

Hope it can help you.

 

#laravel #laravel-9x