Skip to content

Instantly share code, notes, and snippets.

@YasserElgammal
Last active September 9, 2025 21:04
Show Gist options
  • Select an option

  • Save YasserElgammal/8629ce93ce9f8b6e9afba89cf7a756f1 to your computer and use it in GitHub Desktop.

Select an option

Save YasserElgammal/8629ce93ce9f8b6e9afba89cf7a756f1 to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Number;
if (!function_exists('diskStorageStatistics')) {
/**
* Get storage statistics for a given disk.
*
* @param string $disk
* @param bool $includeRoot
* @param string $sort
* @return Collection
*/
function diskStorageStatistics(string $disk = 'public', bool $includeRoot = false, string $sort = 'desc'): Collection
{
$fs = Storage::disk($disk);
$directories = collect($fs->allDirectories());
if ($includeRoot) {
$directories = collect([''])->merge($directories);
}
$data = $directories->map(function (string $folder) use ($fs) {
$files = $folder === '' ? $fs->allFiles() : $fs->allFiles($folder);
$bytes = collect($files)->sum(fn($file) => (int) $fs->size($file));
return [
'folder' => $folder === '' ? '/' : $folder,
'in_bytes' => $bytes,
'human_readable' => Number::fileSize($bytes),
];
});
return $data->sortBy('in_bytes', descending: $sort !== 'asc')->values();
}
}
// Usage
diskStorageStatistics(disk: 'public', includeRoot: true, sort: 'asc');
/* Return as collection
Illuminate\Support\Collection {#1024 // app\Http\Requests\.....
#items: array:3 [
0 => array:3 [
"folder" => "images"
"in_bytes" => 23448
"human_readable" => "23 KB"
]
1 => array:3 [
"folder" => "images/providers"
"in_bytes" => 23448
"human_readable" => "23 KB"
]
2 => array:3 [
"folder" => "/"
"in_bytes" => 23462
"human_readable" => "23 KB"
]
]
#escapeWhenCastingToString: false
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment