Search code examples
filelaravellaravel-5storagefilesize

Laravel 5 Get size from all files inside a directory


Im trying to make a simple file manager in laravel, really I just want to see all the files from 'files' folder, and using laravel Storage I managed to get the name from all the files inside the folder, but i want to get more data like the size of each file.

Controller:

public function showFiles() {
    $files =  Storage::disk('publicfiles')->files();
    return view('files')->with('files', $files);
}

View:

@foreach($files as $file)
    <tr>
        <td>{{$file}}</td>
        <td></td>
        <td class="actions-hover actions-fade">
            <a href=""><i class="fa fa-download"></i></a>
        </td>
    </tr>
@endforeach

Getting this .

As I said I want to get the size, but how could I do that, I tought about processing that in the view but I don't really want to do that.

That being said, I actually know how to do it like this:

@foreach($files as $file)
    <tr>
        <td>{{$file}}</td>
        <td>
        <?php
        $size = Storage::disk('publicfiles')->size($file);
        echo $size;
        ?>

        </td>
        <td class="actions-hover actions-fade">
            <a href=""><i class="fa fa-download"></i></a>
        </td>
    </tr>
@endforeach

But I think it is not right to do that in the view right?


Solution

  • Yes doing that in view isn't a good idea. Just change your controller method like this:

    public function showFiles() {
      $files_with_size = array();
      $files = Storage::disk('publicfiles')->files();
      foreach ($files as $key => $file) {
        $files_with_size[$key]['name'] = $file;
        $files_with_size[$key]['size'] = Storage::disk('publicfiles')->size($file);
      }
      dd($files_with_size);
    }
    

    Or, you can even make a helper function for the same.