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
    

    (No service provider or package discovery needed—auto-discovery handles registration.)

  2. First Use Case: Generate a UUID in a controller or command:

    use Webpatser\Uuid\Uuid;
    
    $uuid = Uuid::generate(); // Defaults to version 4 (random)
    // OR use Str macros:
    use Illuminate\Support\Str;
    $uuid = Str::fastUuid(); // 15% faster than Str::uuid()
    
  3. Database Column Setup: For Eloquent models, use the HasUuids trait:

    use Webpatser\Uuid\HasUuids;
    
    class User extends Model
    {
        use HasUuids;
        // Automatically casts 'id' to UUID string
    }
    
  4. Migrations: Use BinaryUuidMigrations for optimized column types:

    use Webpatser\Uuid\BinaryUuidMigrations;
    
    Schema::create('users', function (Blueprint $table) {
        BinaryUuidMigrations::uuid($table); // Auto-detects database for binary/string
        $table->string('name');
        $table->timestamps();
    });
    

Implementation Patterns

Core Workflows

1. UUID Generation

  • Str Macros (Recommended for performance):
    Str::fastUuid();          // Version 4 (random), 15% faster
    Str::timeBasedUuid();     // Version 1 (time-based)
    Str::nameUuidSha1('name');// Version 3 (name-based)
    
  • Facade Methods:
    Uuid::generate();         // Defaults to version 4
    Uuid::generate(1);        // Explicit version
    

2. Model Integration

  • String UUIDs (Default for SQLite/SQL Server):
    use HasUuids;
    
    class Post extends Model
    {
        use HasUuids;
        protected $keyType = 'string';
    }
    
  • Binary UUIDs (MySQL/PostgreSQL):
    use HasBinaryUuids;
    
    class Post extends Model
    {
        use HasBinaryUuids;
        // Automatically casts to/from binary
    }
    

3. Database Migrations

  • Cross-Database Support:
    Schema::create('posts', function (Blueprint $table) {
        BinaryUuidMigrations::uuid($table); // Auto-selects:
        // - `binary(16)` for MySQL/PostgreSQL
        // - `char(36)` for SQLite/SQL Server
        $table->string('title');
    });
    

4. SQL Server Specifics

  • Byte Order Conversion:
    $sqlServerGuid = Str::uuidToSqlServer($uuid);
    $standardUuid = Str::sqlServerBinaryToUuid($sqlServerGuid);
    
  • Migration Helper:
    BinaryUuidMigrations::sqlServerUuid($table); // Uses `uniqueidentifier`
    

5. Validation

  • Form Requests:
    use Illuminate\Validation\Rules\Uuid;
    
    public function rules()
    {
        return [
            'user_id' => ['required', new Uuid],
        ];
    }
    

6. Route Model Binding

  • Automatic UUID Resolution:
    Route::get('/posts/{post}', function (Post $post) {
        // $post->id is automatically resolved as UUID
    });
    

Integration Tips

API Responses

Binary UUIDs require casting to strings for JSON:

// In AppServiceProvider boot():
Model::macro('toArray', function () {
    $array = parent::toArray();
    if (isset($array['id']) && is_string($array['id']) && strlen($array['id']) === 32) {
        $array['id'] = Str::uuidToString($array['id']); // Cast binary to string
    }
    return $array;
});

Foreign Key Relationships

// Binary UUID FK (MySQL/PostgreSQL)
$table->binaryUuid('user_id')->constrained();

// String UUID FK (SQLite/SQL Server)
$table->uuid('user_id')->constrained();

Seeding

public function run()
{
    User::factory()->count(10)->create([
        'id' => Str::fastUuid(), // Explicit UUID for seed data
    ]);
}

Testing

Use Uuid::generate() for deterministic test IDs:

$uuid = Uuid::generate(1); // Version 1 (time-based, predictable)
User::factory()->create(['id' => $uuid]);

Gotchas and Tips

Pitfalls

  1. Binary UUID Serialization:

    • Issue: Binary UUIDs (16-byte) may serialize as binary in JSON APIs, breaking clients expecting strings.
    • Fix: Use BinaryUuidCast or manually cast in toArray():
      $model->id = Str::uuidToString($model->id); // Before JSON encode
      
  2. SQLite Limitations:

    • Issue: SQLite doesn’t support binary UUIDs; forces string storage, negating performance benefits.
    • Fix: Use HasUuids trait instead of HasBinaryUuids for SQLite.
  3. SQL Server Byte Order:

    • Issue: SQL Server’s uniqueidentifier uses mixed-endianness, causing mismatches with standard UUIDs.
    • Fix: Always use Str::uuidToSqlServer() when inserting into SQL Server and Str::sqlServerBinaryToUuid() when reading.
  4. Route Model Binding:

    • Issue: Binary UUIDs may fail binding if not cast to strings in routes.
    • Fix: Ensure route parameters are strings:
      Route::get('/posts/{post}', function (Post $post) {
          // Works if $post->id is string or binary (auto-cast)
      });
      
  5. UUID Version Confusion:

    • Issue: Str::uuid() (Laravel default) generates version 4, while Str::timeBasedUuid() generates version 1. Mixing versions can cause issues in distributed systems.
    • Fix: Standardize on one version per system (e.g., version 1 for time-based IDs).
  6. Migration Downgrades:

    • Issue: Downgrading from binary to string UUIDs requires data migration (binary → string conversion).
    • Fix: Use Str::uuidToString() in a data migration:
      DB::table('users')->update(['id' => Str::uuidToString('id')]);
      

Debugging Tips

  1. Validate UUIDs:

    if (!Str::fastIsUuid($value)) {
        throw new \InvalidArgumentException('Invalid UUID');
    }
    
  2. Inspect Binary UUIDs:

    $binaryUuid = Str::uuidToBinary($uuid);
    dd(bin2hex($binaryUuid)); // Hex representation for debugging
    
  3. SQL Server GUID Issues:

    • Check for byte order errors by comparing:
      $standard = Str::uuidToBinary($uuid);
      $sqlServer = Str::uuidToSqlServerBinary($uuid);
      dd(hexdec(bin2hex($standard)) === hexdec(bin2hex($sqlServer))); // Should be false
      
  4. Performance Bottlenecks:

    • Benchmark fastUuid() vs. uuid():
      $time = microtime(true);
      for ($i = 0; $i < 10000; $i++) {
          Str::fastUuid();
      }
      echo microtime(true) - $time; // Compare with Str::uuid()
      

Extension Points

  1. Custom UUID Versions: Extend webpatser/uuid to support UUIDv7/v8:

    // In a service provider:
    Str::macro('customUuid', function () {
        return Uuid::generate(8); // UUIDv8
    });
    
  2. Database-Specific Casts: Override BinaryUuidCast for custom storage:

    class CustomBinaryUuidCast implements CastsAttributes
    {
        public function get($model, string $key, $value, array $attributes)
        {
            return Str::uuidToBinary($value);
        }
        public function set($model, string $key, $value, array $attributes)
        {
            return Str::uuidToString($value);
        }
    }
    
  3. Migration Helpers: Add support for new databases:

    BinaryUuidMigrations::extend(function (Blueprint $table, string $column) {
        // Custom logic for Oracle, etc.
    });
    
  4. Validation Rules: Extend the Uuid rule for custom formats:

    use Illuminate\Validation\Rules\Uuid as BaseUuid
    
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.
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
anil/file-picker
broqit/fields-ai