fightstarr20
fightstarr20

Reputation: 12598

Laravel get array of filenames from folder

I am getting an array of filenames from a folder like this...

$files = File::allFiles('myfolder/');

But the resulting array contains pathname as well.

Is there a way of just getting an array of filenames? Or do I need to process each array item and extract the filename from it?

Upvotes: 7

Views: 16636

Answers (3)

convers39
convers39

Reputation: 322

try the laravel Storage api:

use Illuminate\Support\Facades\Storage;

//...

$files = Storage::disk('diskName')->allFiles('folderName');
$fileNames = array_map(function($file){
    return basename($file); // remove the folder name
}, $files);
          


Upvotes: 0

Habib Mammadov
Habib Mammadov

Reputation: 321

hope it helps:

public function parse() {
    $fileNames = [];
    $path = public_path('other');
    $files = \File::allFiles($path);

    foreach($files as $file) {
        array_push($fileNames, pathinfo($file)['filename']);
    }

    dd($fileNames);
}

Upvotes: 3

Sakshi Garg
Sakshi Garg

Reputation: 559

There is an another way of getting file name:

public function index() {

    $filesInFolder = \File::files('folder');     
    foreach($filesInFolder as $path) { 
          $file = pathinfo($path);
          echo $file['filename'] ;
     } 
} 

The pathinfo will gives you the output:

{ "dirname":"file_path", "basename":"file_name.file_extension", "extension":"file_extension", "filename":"file_name" }

Upvotes: 18

Related Questions