zenstruck/bytes
Small PHP bytes utility for working with file sizes: parse human-readable strings (e.g. "10 MB"), format byte counts, compare values, and convert between units. Handy for Laravel/PHP apps needing consistent size handling and validation.
zenstruck/bytes package excels in scenarios requiring byte manipulation, parsing, and human-readable formatting (e.g., file sizes, memory usage, network data). It aligns well with Laravel’s ecosystem, where such utilities are frequently needed for:
Content-Length headers, payload size hints).Storage, Response, Log) and third-party packages (e.g., spatie/laravel-medialibrary, intervention/image).1024 bytes → "1.0 KB") is universally useful.composer require zenstruck/bytes).Bytes::of('1MB') → 1048576 (supports binary/decimal units).Bytes::of(1048576)->human() → "1.0 MB" (configurable precision).Bytes::of(1048576)->format('%.2n B') → "1.00 MB" (ICU-style syntax).Bytes::of('1GB')->gt(Bytes::of('500MB')) → true.AppServiceProvider to auto-humanize bytes in Blade templates or API responses (e.g., {{ $fileSize->human() }}).1.0 MB vs. 1,0 MB). Requires intl extension for non-English locales.1.00 MB vs. 1 MB).1.0 MB) or adapt to user preferences?spatie/laravel-medialibrary to humanize file sizes in media metadata.laravel/framework’s Response to set accurate Content-Length headers.Artisan commands for disk usage reports.formatBytes() functions, regex-based parsing).zenstruck/bytes in critical paths (e.g., file upload validation).AppServiceProvider to add global helpers (e.g., bytes()->human($value)).deprecated() helper or feature flags.spatie/laravel-activitylog (log file size changes).laravel-excel/maatwebsite (humanize CSV/Excel file sizes).| Priority | Task | Dependencies |
|---|---|---|
| High | Replace custom byte parsing in file uploads/storage | None |
| High | Add global bytes() helper to AppServiceProvider |
Core package installed |
| Medium | Update API responses to use humanized sizes | Global helper in place |
| Low | Integrate with CLI tools (e.g., php artisan storage:link --size) |
Optional |
Bytes::of('invalid') throws InvalidArgumentException).round($bytes / 1024, 2)) if the package fails.| Scenario | Impact | Mitigation |
|---|---|---|
| Invalid Input | Bytes::of('invalid') throws exception |
Validate inputs early (e.g., filter_var($size, FILTER_VALIDATE_FLOAT)). |
| Locale Mismatch | Non-English decimal separators (e.g., 1,0 MB) |
Set setlocale() or use Bytes::of()->format('%.2f B') for raw control. |
| Package Removal | Custom logic must be reintroduced | Document all byte-handling dependencies; avoid tight coupling. |
| PHP Extension Missing | intl extension required for some locales |
Fallback to basic formatting or require intl in composer.json. |
0 bytes, Bytes::of('1YB') for "yottabytes").zenstruck/bytes for new byte-related logic.spatie/laravel-medialibrary or API responses.composer.json requires or custom logging.How can I help you explore Laravel packages today?