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 Eloquent Uuid Laravel Package

goldspecdigital/laravel-eloquent-uuid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require goldspecdigital/laravel-eloquent-uuid
    

    Run migrations (if using the default uuid column type):

    php artisan migrate
    
  2. Configure Models: Extend your Eloquent models with HasUUID trait:

    use GoldspecDigital\LaravelEloquentUuid\HasUUID;
    
    class User extends Model
    {
        use HasUUID;
    }
    
  3. First Use Case:

    • Create a new model instance:

      $user = User::create(['name' => 'John Doe']);
      

      The id will now be a UUID (e.g., 123e4567-e89b-12d3-a456-426614174000).

    • Query by UUID:

      $user = User::find('123e4567-e89b-12d3-a456-426614174000');
      

Key Files to Review

  • config/eloquent-uuid.php: Customize UUID generation (e.g., version, namespace).
  • app/Models/YourModel.php: Ensure HasUUID is used.
  • Migrations: Verify column type (e.g., uuid for PostgreSQL, char(36) for MySQL).

Implementation Patterns

Core Workflows

  1. Model Integration:

    • Trait Usage: Apply HasUUID to all models requiring UUIDs.
    • Mass Assignment: Explicitly allow uuid in $fillable if needed (though UUIDs are auto-generated):
      protected $fillable = ['name', 'email']; // UUID is auto-generated
      
  2. UUID Generation:

    • Default Behavior: Uses Ramsey\Uuid\Uuid::uuid4() (random UUID).
    • Customization: Override getIncrementing() and getKeyType():
      public function getIncrementing()
      {
          return false;
      }
      
      public function getKeyType()
      {
          return 'string';
      }
      
  3. Database Schema:

    • PostgreSQL: Use uuid column type.
    • MySQL/MariaDB: Use char(36) or binary(16).
    • SQLite: Use char(36) (no native UUID support).
  4. Relationships:

    • Foreign keys in related tables should also use UUIDs:
      // Migration for posts table
      Schema::create('posts', function (Blueprint $table) {
          $table->uuid('user_id')->constrained()->onDelete('cascade');
          // ...
      });
      
  5. APIs and Serialization:

    • UUIDs work seamlessly with Laravel's JSON responses and API resources.
    • Example resource:
      public function toArray($request)
      {
          return [
              'id' => $this->id, // UUID string
              'name' => $this->name,
          ];
      }
      
  6. Seeding:

    • Use Str::uuid() or Ramsey\Uuid\Uuid::uuid4() in seeders:
      $user = User::create([
          'name' => 'Test User',
          'uuid' => Str::uuid(), // Optional: manually set UUID
      ]);
      

Integration Tips

  • Existing Projects:

    • Run a migration to convert auto-increment IDs to UUIDs:
      // Example migration
      Schema::table('users', function (Blueprint $table) {
          $table->uuid('id')->default(DB::raw('(SELECT uuid_generate_v4())));
          $table->dropPrimary(['id']);
          $table->primary('id');
      });
      
    • Update foreign keys in related tables to reference the new UUID format.
  • Testing:

    • Use HasFactory with UUIDs:
      public function defineModelFactory()
      {
          return UserFactory::new()->state([
              'uuid' => Str::uuid(),
          ]);
      }
      
  • Caching:

    • UUIDs work well with Laravel's cache keys (e.g., cache()->put("user:{$user->id}", $user)).

Gotchas and Tips

Pitfalls

  1. Foreign Key Constraints:

    • Ensure foreign key columns in related tables match the UUID type (e.g., uuid in PostgreSQL, char(36) in MySQL).
    • Example error: SQLSTATE[23000]: Integrity constraint violation: 1235 Column count doesn't match value count (mismatched column types).
  2. Auto-Increment Conflicts:

    • If a model has incrementing = true (default), UUIDs will be ignored. Always set:
      public function getIncrementing()
      {
          return false;
      }
      
  3. UUID Length in MySQL:

    • Using char(36) for UUIDs in MySQL may cause issues with indexing or storage. Consider binary(16) for better performance:
      $table->binary('id')->as('uuid')->primary();
      
  4. Case Sensitivity:

    • UUIDs are case-sensitive in some databases (e.g., PostgreSQL). Ensure consistent casing when querying:
      // Avoid case mismatches
      $user = User::where('id', strtolower($uuid))->first();
      
  5. Legacy Code:

    • Older code assuming integer IDs may break (e.g., User::find(1)). Update all queries to handle UUIDs:
      // Old (breaks)
      $user = User::find(1);
      
      // New
      $user = User::find('123e4567-e89b-12d3-a456-426614174000');
      
  6. UUID Generation in Tests:

    • Avoid hardcoding UUIDs in tests. Use factories or Str::uuid():
      // Bad: Hardcoded UUID
      $user = User::find('123e4567-e89b-12d3-a456-426614174000');
      
      // Good: Dynamic UUID
      $user = User::factory()->create();
      

Debugging

  1. Query Issues:

    • Check if the UUID column exists and is correctly typed in the database:
      php artisan schema:dump
      
    • Verify the column is marked as primary:
      php artisan db:show users
      
  2. Performance:

    • UUIDs can be slower for indexing in some databases. Use database-specific optimizations:
      • PostgreSQL: Use uuid-ossp extension for faster generation.
      • MySQL: Use binary(16) instead of char(36).
  3. Package Conflicts:

    • If using other UUID packages (e.g., webpatser/laravel-uuid), remove them to avoid conflicts:
      composer remove webpatser/laravel-uuid
      

Extension Points

  1. Custom UUID Generation:

    • Override the bootHasUUID() method in your model:
      protected static function bootHasUUID()
      {
          static::creating(function ($model) {
              $model->uuid = Str::orderedUuid(); // Custom logic
          });
      }
      
  2. UUID Versioning:

    • Configure UUID version in config/eloquent-uuid.php:
      'version' => 1, // Use UUIDv1 (time-based)
      
  3. UUID Namespaces:

    • Set a custom namespace for UUIDv1:
      'namespace' => '123e4567-e89b-12d3-a456-426614174000', // Your namespace UUID
      
  4. Hybrid Keys:

    • Combine UUIDs with other keys (e.g., tenant ID + UUID):
      public function getRouteKeyName()
      {
          return ['tenant_id', 'uuid'];
      }
      
  5. UUID Casting:

    • Cast UUIDs to strings in API responses:
      protected $casts = [
          'id' => 'string',
      ];
      

Pro Tips

  1. UUID Shortening:

    • Use packages like ramsey/uuid to shorten UUIDs for URLs (e.g., base64 encoding):
      use Ramsey\Uuid\Uuid;
      
      $shortUuid = base64_encode(Uuid::uuid4()->getBytes());
      
  2. Bulk Operations:

    • UUIDs work well with insert and update statements:
      User::insert([
          ['name' => 'User 1', 'uuid' => Str::uuid()],
          ['name' => 'User 2', 'uuid
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware