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