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

Provides polyfills for the uuid extension, adding uuid_* functions on PHP versions where the extension isn’t available. Part of Symfony’s Polyfill suite; lightweight drop-in to improve portability across environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer (Laravel already includes it as part of symfony/polyfill bundle):

    composer require symfony/polyfill-uuid
    

    Note: If using Laravel 5.7+, this is often auto-included via symfony/polyfill.

  2. First Use Case: Generate a UUID in a Laravel migration or model:

    // Migration
    Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->default(\Ramsey\Uuid\Uuid::uuid4()); // Works with polyfill
        // OR
        $table->uuid('id')->default(\Str::uuid()); // Laravel facade
    });
    
    // Model
    $user = new User();
    $user->uuid = \Str::uuid(); // Uses polyfill under the hood
    
  3. Verify Functionality: Test UUID generation in a Tinker session:

    php artisan tinker
    >>> \Str::uuid();
    // Output: e.g., "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
    

Where to Look First


Implementation Patterns

Usage Patterns

  1. Laravel Migrations:

    $table->uuid('id')->default(\uuid_generate_v4());
    // OR
    $table->uuid('id')->default(\Str::uuid());
    
  2. Eloquent Models:

    use Illuminate\Support\Str;
    
    class User extends Model {
        protected static function boot() {
            parent::boot();
            static::creating(function ($model) {
                $model->uuid = Str::uuid(); // Auto-generate UUID
            });
        }
    }
    
  3. API Responses:

    return response()->json([
        'data' => [
            'id' => Str::uuid(), // Generate UUID on-the-fly
            'name' => 'John Doe',
        ],
    ]);
    
  4. Factories:

    $factory->define(User::class, function (Faker $faker) {
        return [
            'uuid' => Str::uuid(),
            // ...
        ];
    });
    

Workflows

  1. UUID Generation in Services:

    class OrderService {
        public function createOrder() {
            $order = new Order();
            $order->order_id = Str::uuid(); // Reusable logic
            $order->save();
            return $order;
        }
    }
    
  2. Bulk UUID Generation:

    $uuids = collect(range(1, 100))->map(fn() => Str::uuid());
    // Useful for seeding or batch operations.
    
  3. Validation:

    use Illuminate\Validation\Rule;
    
    $request->validate([
        'uuid' => ['required', Rule::uuid()],
    ]);
    

Integration Tips

  • Leverage Laravel’s Str Facade: Prefer Str::uuid() for consistency across the codebase.
  • Use in Migrations: Replace hardcoded UUIDs with uuid_generate_v4() for dynamic defaults.
  • Combine with ramsey/uuid: For advanced use cases (e.g., version 1/3/5 UUIDs), use ramsey/uuid alongside the polyfill:
    use Ramsey\Uuid\Uuid;
    
    $uuid = Uuid::uuid4(); // Works with polyfill if ext-uuid is unavailable
    
  • Testing: Mock UUID generation in tests to ensure determinism:
    $this->app->singleton(\Illuminate\Support\Str::class, function () {
        return new class extends \Illuminate\Support\Str {
            public static function uuid() {
                return 'fixed-uuid-for-testing';
            }
        };
    });
    

Gotchas and Tips

Pitfalls

  1. Entropy Issues in Containers/CI:

    • Problem: random_bytes() may fail in environments with insufficient entropy (e.g., Docker without --cap-add=SYS_RANDOM or CI pipelines).
    • Fix: Add entropy sources or use a fallback:
      if (!\random_bytes(16)) {
          throw new \RuntimeException('Failed to generate UUID: insufficient entropy.');
      }
      
    • Docker Fix: Run containers with:
      docker run --cap-add=SYS_RANDOM ...
      
  2. Performance Overhead:

    • Problem: Polyfill is ~10–30% slower than native ext-uuid.
    • Fix: Enable ext-uuid in PHP 8.0+ for performance-critical paths:
      ; php.ini
      extension=uuid
      
    • Benchmark: Test with phpbench if generating >10K UUIDs/sec.
  3. Version Conflicts:

    • Problem: Older Laravel versions (<5.7) may not auto-include the polyfill.
    • Fix: Explicitly require symfony/polyfill-uuid in composer.json.
  4. Hardcoded UUIDs:

    • Problem: Hardcoded UUIDs (e.g., in tests or configs) may conflict with dynamic generation.
    • Fix: Use Str::uuid() or uuid_generate_v4() for consistency.
  5. No Version 1/3/5 Support:

    • Problem: Polyfill only supports v4 UUIDs (random). For time/namespace-based UUIDs, use ramsey/uuid.
    • Fix: Install ramsey/uuid separately:
      composer require ramsey/uuid
      

Debugging

  1. UUID Validation:

    • Validate UUIDs in tests or production:
      use Illuminate\Validation\Rule;
      
      $request->validate([
          'uuid' => ['required', Rule::uuid()],
      ]);
      
  2. Check for Polyfill Usage:

    • Verify the polyfill is loaded:
      php artisan tinker
      >>> class_uses(\Illuminate\Support\Str::class);
      // Should include symfony/polyfill-uuid if active.
      
  3. Entropy Debugging:

    • Test random_bytes() in CI/CD:
      if (!\random_bytes(16)) {
          \Log::error('UUID generation failed: entropy issue');
      }
      

Tips

  1. Laravel-Specific Shortcuts:

    • Use Str::uuid() for Laravel apps (auto-included in Laravel 5.7+).
    • For migrations, prefer uuid_generate_v4() for clarity.
  2. Hybrid Approach:

    • Combine with ext-uuid for PHP 8.0+:
      if (function_exists('uuid_create')) {
          $uuid = uuid_create(UUID_TYPE_RANDOM);
      } else {
          $uuid = Str::uuid();
      }
      
  3. Testing UUIDs:

    • Mock UUIDs in tests to avoid flakiness:
      $this->app->singleton(\Illuminate\Support\Str::class, function () {
          return new class extends \Illuminate\Support\Str {
              public static function uuid() {
                  return 'test-uuid-123';
              }
          };
      });
      
  4. Performance Optimization:

    • Cache UUIDs if generating in bulk (e.g., for seeding):
      $uuids = collect(range(1, 1000))->map(fn() => Str::uuid())->toArray();
      
  5. Compliance:

    • For audit trails, log UUID generation sources (e.g., Str::uuid() vs. ramsey/uuid):
      \Log::debug('Generated UUID via Str::uuid()', ['uuid' => Str::uuid()]);
      
  6. CI/CD Entropy:

    • Add entropy to Docker/CI environments:
      # Docker
      docker run --cap-add=SYS_RANDOM ...
      
      # GitHub Actions
      - name: Ensure entropy
        run: |
          sudo apt-get install -y haveged
          sudo service haveged start
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope