Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

File::files() response returns array of empty objects

I’m trying to fetch a list of files in my Laravel application through the Files facade, but it’s not working as expected.

$path = storage_path('path/to/folder/' . $request->folder);
$files = File::files($path);
return response()->json($files, 200);

This is the code I’m running. There are currently 5 files in the directory I’m using to test this out.

The response shows the correct amount of files as objects inside an array, but all of them are empty.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

The path I’m aiming at is correct, the files exist and adding/removing files reflects as expected in the response. But I don’t understand why the objects are empty.

What am I missing?

>Solution :

You can get information about the files in the directory by accessing the properties and methods of SplFileInfo objects.

$path = storage_path('path/to/folder/' . $request->folder);
$files = File::files($path);

$fileDetails = [];

foreach ($files as $file) {
    $fileDetails[] = [
        'name' => $file->getFilename(),
        'path' => $file->getRealPath(),
        'size' => $file->getSize(),
        'lastModified' => $file->getMTime(),
    ];
}

return response()->json($fileDetails, 200);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading