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

michalkortas/laravel-uuid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run composer require michalkortas/laravel-uuid in your project root. Publish the config (if needed) with php artisan vendor:publish --provider="michalkortas\LaravelUuid\LaravelUuidServiceProvider".

  2. Migration Modify your migration to use UUID for the primary key:

    Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary(); // CHAR(36) in DB
        // ...
    });
    
  3. Model Integration Add the HasUuid trait to your Eloquent model:

    use michalkortas\LaravelUuid\traits\HasUuid;
    
    class User extends Model
    {
        use HasUuid;
    }
    
  4. First Use Case Create a record—UUIDs will auto-generate:

    $user = User::create(['name' => 'John Doe']);
    // $user->id is now a UUID string (e.g., "123e4567-e89b-12d3-a456-426614174000")
    

Implementation Patterns

Workflows

  1. Auto-Generation The trait automatically handles UUID generation on create() and save(). No manual intervention needed for new records.

  2. Querying with UUIDs Use UUIDs in queries like any other field:

    User::where('id', $uuidString)->first();
    // or
    User::find($uuidString); // Works due to trait's $primaryKey override
    
  3. Seeding UUIDs work seamlessly with Laravel’s DatabaseSeeder:

    User::create(['name' => 'Admin']);
    // UUID auto-assigned
    
  4. Relationships Define relationships as usual—UUIDs are treated as primary keys:

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
    
  5. API Responses UUIDs serialize naturally in JSON:

    {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "John Doe"
    }
    

Integration Tips

  • Existing Tables For tables without UUIDs, add a uuid column and update the model’s $primaryKey:

    protected $primaryKey = 'uuid';
    public $incrementing = false;
    

    Use HasUuid trait for auto-generation.

  • Custom UUID Generation Override the generateUuid() method in your model:

    protected function generateUuid()
    {
        return Str::uuid()->toString(); // Custom logic
    }
    
  • Database Constraints Ensure your database supports UUIDs (e.g., PostgreSQL, MySQL 8+ with CHAR(36)).


Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • If you add a UUID column to an existing table, ensure the column is nullable during migration:
      $table->uuid('uuid')->nullable()->after('id');
      
    • Run php artisan migrate:fresh if UUIDs conflict with auto-incrementing IDs.
  2. Primary Key Overrides

    • Forgetting to set $incrementing = false can cause issues with UUIDs.
    • Always define protected $primaryKey = 'id'; (or your UUID column name) in the model.
  3. Query Builder Quirks

    • Avoid Model::findOrFail($uuid) if $uuid is not a string (e.g., pass "123e4..." instead of 123e4...).
  4. Foreign Key Mismatches

    • When defining foreign keys, use uuid() in migrations:
      $table->uuid('user_id')->foreign();
      

Debugging

  • UUID Not Generated? Check if the HasUuid trait is applied and the migration uses $table->uuid('id')->primary(). Verify the model’s $primaryKey matches the UUID column name.

  • Duplicate UUIDs? The package uses Laravel’s Str::uuid(), which is collision-resistant. If duplicates occur, manually override generateUuid() with a deterministic logic (e.g., Ramsey\Uuid\Uuid::uuid4()).

Extension Points

  1. Custom UUID Format Override getKeyType() in your model:

    public function getKeyType()
    {
        return 'string'; // Ensures UUIDs are treated as strings
    }
    
  2. UUID Validation Add validation rules for UUID fields:

    use Illuminate\Validation\Rule;
    
    $request->validate([
        'id' => ['required', Rule::uuid()],
    ]);
    
  3. UUID as Non-Primary Key Use the trait for non-primary UUID fields:

    $table->uuid('external_id');
    

    In the model:

    use HasUuid;
    
    protected $primaryKey = 'id'; // Keep auto-increment as primary
    protected $uuidField = 'external_id'; // Customize trait behavior
    
  4. Performance For large datasets, consider indexing UUID columns:

    $table->uuid('id')->primary()->index();
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony