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

Polyfill Uuid Laravel Package

symfony/polyfill-uuid

Symfony Polyfill for UUID brings uuid_* functions to PHP environments that don’t have the uuid extension installed. It lets applications use common UUID helpers consistently across PHP versions, matching Symfony’s polyfill approach and staying lightweight and MIT licensed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer (often auto-included with Laravel’s symfony/polyfill bundle):

    composer require symfony/polyfill-uuid
    

    Note: Laravel 8+ includes this polyfill by default in its symfony/polyfill package.

  2. First Use Case: Replace custom UUID generation with built-in functions:

    // Generate a v4 UUID (RFC 4122 compliant)
    $uuid = uuid_generate_v4(); // e.g., "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"
    
    // Laravel Str facade (if available)
    $uuid = Str::uuid();
    
  3. Where to Look First:

    • Laravel Migrations: Replace hardcoded UUIDs or custom logic:
      $table->uuid('id')->default(uuid_generate_v4());
      
    • Eloquent Models: Use Str::uuid() for default values or factories:
      $model->uuid = Str::uuid();
      
    • API Responses: Standardize UUID generation for consistency.

Implementation Patterns

Usage Patterns

  1. Laravel-Centric Workflows:

    • Migrations: Generate UUIDs for primary keys or unique identifiers:
      Schema::create('users', function (Blueprint $table) {
          $table->uuid('id')->default(uuid_generate_v4());
          $table->string('name');
          $table->timestamps();
      });
      
    • Factories: Seed UUIDs in test data:
      User::factory()->create(['uuid' => Str::uuid()]);
      
    • APIs: Return consistent UUIDs in responses:
      return response()->json(['uuid' => Str::uuid()]);
      
  2. Symfony Integration:

    • Use with Symfony components (e.g., Symfony\Component\Uid\Uuid if available):
      use Symfony\Component\Uid\Uuid;
      $uuid = Uuid::v4()->toRfc4122();
      
    • Note: The polyfill ensures backward compatibility if Symfony’s Uid component is later adopted.
  3. Cross-Environment Consistency:

    • Serverless/Containerized: Works in AWS Lambda, Heroku, or Docker without ext-uuid:
      // Lambda function example
      return [
          'id' => uuid_generate_v4(),
          'data' => $request['payload']
      ];
      
    • Shared Hosting: Avoids PECL extension restrictions.
  4. Legacy Code Modernization:

    • Replace custom UUID logic (e.g., ramsey/uuid, voku/uuid) with polyfill functions:
      // Before
      $uuid = \Ramsey\Uuid\Uuid::uuid4()->toString();
      
      // After
      $uuid = uuid_generate_v4();
      

Integration Tips

  1. Leverage Laravel’s Str Facade: If using Laravel, prefer Str::uuid() for consistency:

    use Illuminate\Support\Str;
    $uuid = Str::uuid(); // Uses polyfill under the hood
    
  2. Database Schema: Use uuid() in migrations for PostgreSQL/MySQL 8+:

    $table->uuid('id')->default(uuid_generate_v4());
    

    Tip: For SQLite, use string(36) and validate UUIDs in application logic.

  3. Testing: Mock UUID generation in tests to avoid flakiness:

    // In a test case
    UUID::shouldReceive('generate')
         ->once()
         ->andReturn('mock-uuid-123');
    
  4. Performance Considerations:

    • Benchmark in high-throughput scenarios (e.g., bulk inserts).
    • Enable ext-uuid in PHP 8.0+ for native performance if possible.
  5. Entropy Validation: Ensure random_bytes() has sufficient entropy in CI/CD or containers:

    # Docker example
    docker run --cap-add=SYS_RANDOM ...
    

Gotchas and Tips

Pitfalls

  1. Entropy Issues:

    • Problem: random_bytes() may fail in low-entropy environments (e.g., Docker without --cap-add=SYS_RANDOM or CI/CD pipelines).
    • Fix: Add entropy sources or mock random_bytes() in tests:
      // Mock in PHPUnit
      $this->replace('random_bytes', fn() => random_bytes(16));
      
  2. PHP Version Quirks:

    • Problem: PHP < 7.0 may lack random_bytes() support (though Laravel typically targets PHP 7.4+).
    • Fix: Use openssl_random_pseudo_bytes() as a fallback:
      if (!function_exists('random_bytes')) {
          $bytes = openssl_random_pseudo_bytes(16);
      }
      
  3. UUID Validation:

    • Problem: Generated UUIDs may not pass strict RFC 4122 validation if entropy is weak.
    • Fix: Validate UUIDs in application logic:
      if (!Uuid::isValid($uuid)) { // Use ramsey/uuid for validation
          throw new \InvalidArgumentException('Invalid UUID');
      }
      
  4. Laravel-Specific Gotchas:

    • Problem: Str::uuid() may not be available in older Laravel versions (< 5.7).
    • Fix: Use uuid_generate_v4() directly or upgrade Laravel.
  5. Database Compatibility:

    • Problem: SQLite doesn’t natively support UUID types.
    • Fix: Use string(36) and validate UUIDs in models:
      protected $casts = [
          'uuid' => 'string',
      ];
      
      public function validateUuidAttribute($value) {
          return Uuid::isValid($value) ?: throw new \InvalidArgumentException();
      }
      

Debugging Tips

  1. Check UUID Format: Ensure generated UUIDs match RFC 4122 (e.g., 1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed):

    $uuid = uuid_generate_v4();
    assert(preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid));
    
  2. Performance Profiling: Compare polyfill vs. native ext-uuid:

    # Benchmark in Laravel
    php artisan tinker
    >>> $start = microtime(true);
    >>> for ($i = 0; $i < 10000; $i++) uuid_generate_v4();
    >>> echo microtime(true) - $start;
    
  3. Entropy Testing: Verify random_bytes() in CI/CD:

    $bytes = random_bytes(16);
    if (strlen($bytes) !== 16) {
        throw new \RuntimeException('Insufficient entropy');
    }
    

Extension Points

  1. Custom UUID Generation: Extend the polyfill’s logic by wrapping uuid_generate_v4():

    function custom_uuid() {
        $uuid = uuid_generate_v4();
        return strtoupper($uuid); // Example: Uppercase UUIDs
    }
    
  2. Fallback for random_bytes: Implement a custom fallback for restricted environments:

    if (!function_exists('random_bytes')) {
        function random_bytes($length) {
            return openssl_random_pseudo_bytes($length);
        }
    }
    
  3. Integration with ramsey/uuid: Use the polyfill for basic generation but ramsey/uuid for validation:

    $uuid = uuid_generate_v4();
    if (!\Ramsey\Uuid\Uuid::isValid($uuid)) {
        // Handle invalid UUID (unlikely but possible)
    }
    
  4. Laravel Service Provider: Bind a custom UUID generator in Laravel’s service container:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind('uuid-generator', function() {
            return new class {
                public function generate() {
                    return uuid_generate_v4();
                }
            };
        });
    }
    

Config Quirks

  1. No Configuration Required: The polyfill auto-loads and requires no manual setup in config/app.php.

  2. Laravel’s Str Facade: Ensure Str::uuid() is available by including the Illuminate\Support\Str facade:

    use Illuminate\Support\Str;
    
  3. PHP Extensions: The polyfill gracefully falls back to native functions if ext-uuid is installed:

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony