Laravel - How to Get All Files in a Directory?

By Hardik Savani September 23, 2022 Category : Laravel

Hello,

This example is focused on how to get all files in a directory laravel. I would like to show you laravel get all files in directory. I explained simply about laravel get all file names in directory. This article goes in detailed on laravel list all files in directory.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

There are several ways to get a list of all files in a directory using laravel php code. i will give you some examples of code to get all files from the folder. we will use laravel Storage facade to get files.

So, let's see the below examples code with output:

Example 1: Laravel Get All Files of Specific Directory

Here, we will use files() function of Storage facade. it will return all files of specific folder.

app/Http/Controllers/DemoController.php

<?php

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);

}

}

Output:

Array

(

[0] => public/output.pdf

[1] => public/.gitignore

[2] => public/test.pdf

)

Example 2: Laravel Get All Files of Directory Recursively

Here, we will use allFiles() function of Storage facade. it will return all files of specific folder with subdirectories files as well.

app/Http/Controllers/DemoController.php

<?php

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);

}

}

Output:

Array

(

[0] => public/output.pdf

[1] => public/uploads/627653f563dde.png

[2] => public/uploads/demo2.txt

[3] => public/uploads/demo3.txt

[4] => public/.gitignore

[5] => public/test.pdf

)

I hope it can help you...

Tags :