Last active
September 9, 2025 21:04
-
-
Save YasserElgammal/8629ce93ce9f8b6e9afba89cf7a756f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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