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

Laravel Uuid Laravel Package

webpatser/laravel-uuid

Laravel package for generating and working with UUIDs. Provides a UUID model trait, helpers to create v1/v4 UUIDs, and integrates with Eloquent so models can use UUID primary keys instead of auto-increment IDs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require webpatser/laravel-uuid
    
    • Automatically registers Str macros and service providers (zero-config).
  2. First Use Case: Generate a UUID in a controller or model:

    use Illuminate\Support\Str;
    
    $uuid = Str::uuid(); // Standard RFC 4122 v4
    $uuid = Str::fastUuid(); // 15% faster alternative
    $uuid = Str::timeBasedUuid(); // RFC 4122 v1 (time-based)
    
  3. Database Column Setup: Use the migration helper for binary UUIDs (recommended for MySQL/PostgreSQL):

    use Webpatser\LaravelUuid\BinaryUuidMigrations;
    
    Schema::create('users', function (Blueprint $table) {
        BinaryUuidMigrations::uuid($table); // Auto-detects database type
        $table->string('name');
        $table->timestamps();
    });
    
  4. Model Integration: Add the HasBinaryUuids trait to your Eloquent model:

    use Webpatser\LaravelUuid\HasBinaryUuids;
    
    class User extends Model
    {
        use HasBinaryUuids;
        // Automatically casts binary UUID to string for APIs
    }
    

Implementation Patterns

Core Workflows

1. UUID Generation Strategies

Use Case Method Notes
General-purpose UUID Str::uuid() RFC 4122 v4 (random)
Time-based UUID Str::timeBasedUuid() RFC 4122 v1 (time + MAC address)
Fast generation Str::fastUuid() 15% faster than Str::uuid()
Name-based UUID Str::nameUuidSha1('name') RFC 4122 v5 (deterministic)
SQL Server GUID Str::uuidToSqlServer($uuid) Converts to uniqueidentifier format

Example: Multi-Version UUID Generation

$versions = [
    'v1' => Str::timeBasedUuid(),
    'v4' => Str::uuid(),
    'v5' => Str::nameUuidSha1('user@example.com'),
];

2. Database Integration

Binary UUID Migrations (Recommended for MySQL/PostgreSQL):

use Webpatser\LaravelUuid\BinaryUuidMigrations;

Schema::create('orders', function (Blueprint $table) {
    BinaryUuidMigrations::uuid($table); // Creates `uuid` column as binary(16)
    $table->foreignId('user_id')->constrained();
    $table->timestamps();
});

SQL Server-Specific Handling:

// Convert standard UUID to SQL Server GUID
$sqlServerGuid = Str::uuidToSqlServer($uuid);

// Convert SQL Server binary GUID back to UUID
$uuid = Str::sqlServerBinaryToUuid($binaryGuid);

SQLite Fallback:

// SQLite doesn't support binary UUIDs; use string storage
$table->uuid('id')->default(Str::uuid());

3. Model Binding and Relationships

Route Model Binding:

// routes/web.php
Route::get('/users/{user}', [UserController::class, 'show']);

// UserController.php
public function show(User $user) {
    // $user->id is automatically cast to string
}

Foreign Key Relationships:

class Order extends Model
{
    use HasBinaryUuids;

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}

Polymorphic Relationships:

$model->morphTo(); // Works with UUID primary keys

4. Validation and API Responses

Validation:

use Illuminate\Validation\Rule;

$validated = Validator::make($request->all(), [
    'uuid' => ['required', 'uuid'],
    'custom_uuid' => [Rule::uuid()],
]);

API Response Casting:

// In AppServiceProvider::boot()
Model::shouldBeCastToType('string', 'uuid');

Manual Casting:

return response()->json([
    'user_id' => (string) $user->id, // Ensures string output
]);

5. Bulk Operations

Fast UUID Generation for Seeders:

public function run()
{
    $uuids = Str::fastUuid()->make(1000); // Generates 1000 UUIDs in bulk
    User::insert([
        'id' => $uuids,
        'name' => 'Test User',
    ]);
}

Batch Insertion with Binary UUIDs:

DB::table('users')->insert([
    'id' => Str::fastUuid()->make(1000),
    'name' => 'Batch User',
]);

Integration Tips

  1. Leverage Str Macros Globally: Add custom UUID methods to app/Providers/AppServiceProvider.php:

    Str::macro('orderedUuid', function () {
        return Str::uuid()->toRfc4122();
    });
    
  2. Database-Specific Config: Use environment variables to toggle binary UUIDs:

    // config/uuid.php
    return [
        'use_binary' => env('DB_CONNECTION') !== 'sqlite',
    ];
    
  3. Testing UUIDs: Use Str::fakeUuid() for deterministic testing:

    $uuid = Str::fakeUuid('550e8400-e29b-41d4-a716-446655440000');
    
  4. Legacy System Migration:

    • Use Str::isUuid() to validate existing IDs.
    • Implement a uuid column alongside id during transition:
      $table->id();
      $table->uuid('uuid')->unique()->default(Str::uuid());
      

Gotchas and Tips

Pitfalls

  1. Binary UUID Serialization:

    • Issue: Binary UUIDs may serialize as \Webpatser\Uuid\Uuid in JSON APIs.
    • Fix: Explicitly cast to string in models or API responses:
      protected $casts = ['id' => 'string'];
      
  2. SQL Server Byte Order:

    • Issue: SQL Server stores GUIDs in mixed-endianness format, causing mismatches.
    • Fix: Always use Str::uuidToSqlServer() for inserts and Str::sqlServerBinaryToUuid() for retrievals.
  3. SQLite Limitations:

    • Issue: SQLite doesn’t support binary UUIDs; forces string storage.
    • Fix: Use Str::uuid() directly and avoid binary migrations:
      $table->string('id')->default(Str::uuid());
      
  4. UUIDv1 Time Dependence:

    • Issue: Str::timeBasedUuid() includes MAC address, causing issues in serverless environments.
    • Fix: Use Str::uuid() (v4) for stateless deployments or mock the MAC address in tests.
  5. Route Model Binding Quirks:

    • Issue: Binary UUIDs may fail binding if not cast to string.
    • Fix: Ensure models use HasBinaryUuids and cast id to string:
      protected $casts = ['id' => 'string'];
      
  6. Foreign Key Constraints:

    • Issue: Binary UUID foreign keys may fail if not properly typed.
    • Fix: Use BinaryUuidMigrations for consistent column types:
      $table->binaryUuid('user_id'); // Explicit binary UUID FK
      

Debugging Tips

  1. UUID Validation Errors:

    • Use Str::isUuid($value) to validate manually:
      if (!Str::isUuid($request->uuid)) {
          throw ValidationException::withMessages(['uuid' => 'Invalid UUID format.']);
      }
      
  2. Binary UUID Storage Issues:

    • Check column type with:
      Schema::getColumnListing('users'); // Should show 'uuid' as binary(16)
      
  3. SQL Server GUID Problems:

    • Verify byte order with:
      $binary = Str::uuidToSqlServerBinary($uuid);
      $uuidBack = Str::sqlServerBinaryToUuid($binary);
      dd($uuid === $uuidBack); // Should be true
      
  4. Performance Bottlenecks:

    • Compare Str::uuid() vs. Str::fastUuid():
      $time = microtime(true);
      for ($i = 0; $i < 1000; $i++) {
          $uuid = Str::fastUuid();
      }
      echo microtime(true) - $
      
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/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
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