Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Bytes Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require zenstruck/bytes
    

    No configuration is required—just autoload the package.

  2. First Use Case: Parse and humanize bytes in a Blade view or controller:

    use Zenstruck\Bytes\Bytes;
    
    $bytes = Bytes::of(1500); // Parse bytes
    echo $bytes->human(); // Outputs: "1.43 KB"
    
  3. Where to Look First:


Implementation Patterns

Common Workflows

  1. Parsing Bytes:

    $bytes = Bytes::of(1024 * 1024); // Parse from integer (e.g., 1MB)
    $bytes = Bytes::of('1MB');       // Parse from string (e.g., "1MB", "2.5GB")
    
  2. Humanizing Output:

    $bytes->human();       // "1 MB"
    $bytes->human('si');   // "1 MiB" (binary SI units)
    $bytes->human('B');    // "1048576 B" (raw bytes)
    
  3. Formatting for APIs/CLI:

    $bytes->format('%01.2f %s'); // "1.00 MB"
    $bytes->format('%s');       // "MB" (unit only)
    
  4. Validation/Constraints:

    use Zenstruck\Bytes\Constraints\MaxBytes;
    
    $validator = Validator::make(['file' => $request->file], [
        'file' => ['required', new MaxBytes(5 * Bytes::MEGA)]
    ]);
    
  5. Laravel Integration:

    • File Uploads:
      $request->file('avatar')->getSize() // Get bytes
          ->human(); // Display to user
      
    • Storage Disk Usage:
      $usage = Storage::disk('s3')->usage();
      Bytes::of($usage)->human(); // "1.2 GB"
      
  6. Testing:

    $this->assertEquals('1.43 KB', Bytes::of(1500)->human());
    

Gotchas and Tips

Pitfalls

  1. Unit Confusion:

    • human() defaults to decimal (SI) units (e.g., "1 MB" = 1,000,000 bytes).
    • Use human('binary') for binary (IEC) units (e.g., "1 MiB" = 1,048,576 bytes).
    • Tip: Document which system your app uses (e.g., Bytes::DECIMAL vs. Bytes::BINARY).
  2. String Parsing Quirks:

    • Supports KB, MB, GB, TB (decimal) and KiB, MiB, GiB, TiB (binary).
    • Case-insensitive but must include the unit (e.g., "1mb" works, "1" fails).
    • Tip: Validate input with Bytes::isValid('1MB') before parsing.
  3. Precision Loss:

    • Floating-point operations may truncate values. Use format() with precision:
      $bytes->format('%.3f %s'); // "1.429 MB" (3 decimal places)
      
  4. Constraint Edge Cases:

    • MaxBytes throws InvalidArgumentException for invalid values. Catch or validate first:
      try {
          Bytes::of($request->input('size'));
      } catch (\InvalidArgumentException $e) {
          return back()->withError('Invalid size format.');
      }
      

Tips

  1. Reusable Helpers: Create a helper for common humanization:

    if (!function_exists('bytes_human')) {
        function bytes_human($bytes, string $unit = 'decimal'): string {
            return Bytes::of($bytes)->human($unit);
        }
    }
    

    Usage: bytes_human(1500)"1.43 KB".

  2. Localization: Extend Humanizer to support custom units/translations:

    $humanizer = new Humanizer(['KB' => 'Kilobyte']);
    Bytes::of(1024)->humanizeWith($humanizer); // "1 Kilobyte"
    
  3. Performance:

    • Parsing is lightweight; cache results for static values:
      $cacheKey = 'max_upload_size';
      $maxSize = Bytes::of(cache($cacheKey) ?? config('filesystems.max_upload'));
      
  4. Debugging:

    • Check raw bytes with ->bytes() to verify parsing:
      $bytes = Bytes::of('1MB');
      $bytes->bytes(); // 1000000 (decimal) or 1048576 (binary)
      
  5. Testing Binary vs. Decimal:

    $this->assertEquals('1 MiB', Bytes::of(1048576)->human('binary'));
    $this->assertEquals('1 MB',  Bytes::of(1000000)->human('decimal'));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor