fefe
fefe

Reputation: 9055

Get file information form directory Laravel

I use the following method to get all files from a folder and my method returns some basic information about the files inside directory

public function getUploaded()
{

    $files = [];
    $filesInFolder = File::files(base_path() .'/'. self::UPLOAD_DIR);

    foreach($filesInFolder as $path)
    {
        $files[] = pathinfo($path);
    }

    return response()->json($files, 200);
}

How would I get the size and the base name like ?

$files['name'] = ....
$files['size'] = ....

Upvotes: 0

Views: 3127

Answers (2)

marcus.ramsden
marcus.ramsden

Reputation: 2633

You could solve this quite neatly with a Laravel collection and SplFileInfo. Something along the following lines;

public function getUploaded()
{
    $files = collect(File::files(base_path() . "/" . self::UPLOAD_DIR))->map(function ($filePath) {
        $file = new \SplFileInfo($filePath);
        return [
            'name' => $file->getName(),
            'size' => $file->getSize(),
        ];
    });

    return response()->json($files);
}

Upvotes: 1

tnash
tnash

Reputation: 385

You can modify your code as follows:

foreach ($filesInFolder as $path) {
   $file = pathinfo($path);
   $file['size'] = File::size($path);
   $file['name'] = File::name($path);
   $files[] = $file;
}

Upvotes: 0

Related Questions