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

Model Uuid Laravel Package

fahriztx/model-uuid

Laravel/PHP trait to add automatic UUIDs to Eloquent models. Generates a UUID when creating records and supports using UUIDs as primary keys or additional identifiers, reducing reliance on auto-increment IDs and easing integration across systems.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require fahriztx/model-uuid
    

    Publish the migration if needed (check vendor/fahriztx/model-uuid/migrations/).

  2. Configure UUID as Primary Key Modify your model’s $keyType and $incrementing properties:

    use FAHRIZTX\ModelUuid\HasUuid;
    
    class User extends Model
    {
        use HasUuid;
    
        protected $keyType = 'string';
        protected $incrementing = false;
    }
    
  3. Run Migrations

    php artisan migrate
    

    The package ensures UUID columns are created with the correct type (e.g., uuid in PostgreSQL, char(36) in MySQL).

  4. First Use Case Create a record and observe UUID generation:

    $user = User::create(['name' => 'John Doe']);
    dd($user->id); // e.g., "550e8400-e29b-41d4-a716-446655440000"
    

Implementation Patterns

Workflows

  1. UUID Generation

    • The package auto-generates UUIDs via Ramsey\Uuid (included).
    • Override generation (e.g., for testing):
      $user = User::forceFill(['id' => 'custom-uuid'])->save();
      
  2. Querying by UUID

    • Use Eloquent’s default find() or where():
      $user = User::find('550e8400-e29b-41d4-a716-446655440000');
      User::where('id', '550e8400-e29b-41d4-a716-446655440000')->first();
      
  3. Relationships

    • Foreign keys must also use UUIDs. Configure related models similarly:
      class Post extends Model
      {
          use HasUuid;
      
          public function user()
          {
              return $this->belongsTo(User::class, 'user_id', 'id');
          }
      }
      
  4. Seeding

    • Use Str::uuid() in seeders or factories:
      User::factory()->create(['id' => Str::uuid()]);
      
  5. API Responses

    • UUIDs serialize naturally in JSON. No extra handling needed.

Integration Tips

  • Database-Specific Setup:

    • PostgreSQL: Uses uuid-ossp extension. Add to config/database.php:
      'postgres' => [
          'extensions' => ['uuid-ossp'],
      ],
      
    • MySQL/MariaDB: Uses char(36) with binary storage for efficiency.
  • Casting:

    • Cast UUIDs to string in API resources if needed:
      public function toArray($request)
      {
          return [
              'id' => $this->id->toString(),
          ];
      }
      
  • Testing:

    • Mock UUIDs in tests:
      $this->partialMock(User::class, 'generateUuid')
           ->shouldReceive('generateUuid')
           ->andReturn('test-uuid');
      

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • If you manually define a primary key column, the package’s migration may fail. Solution: Remove the column from migrations and let the package handle it.
  2. Foreign Key Mismatches

    • Forgetting to set $keyType = 'string' on related models causes ForeignKeyDoesNotMatch errors. Solution: Ensure all related models use HasUuid.
  3. UUID Length in MySQL

    • MySQL’s char(36) may cause index bloat. Solution: Use binary(16) for storage (requires custom casting):
      protected $casts = [
          'id' => 'string',
      ];
      
  4. UUID Collisions

    • While statistically unlikely, collisions can occur. Solution: Validate UUIDs on input:
      use Ramsey\Uuid\Uuid;
      
      public function validateUuid($uuid)
      {
          return Uuid::isValid($uuid);
      }
      

Debugging

  • UUID Not Generated? Check if $incrementing = false and $keyType = 'string' are set. Verify the id column type in the database matches expectations.

  • Slow Queries? UUIDs in indexes may perform worse than integers. Solution: Use database-specific optimizations (e.g., PostgreSQL’s uuid-ossp functions for generation).

Extension Points

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

    protected function generateUuid()
    {
        return Uuid::uuid4()->toString();
    }
    
  2. UUID Validation Add custom validation rules:

    use Illuminate\Validation\Rule;
    
    $request->validate([
        'id' => ['required', Rule::uuid()],
    ]);
    
  3. UUID Formatting Use accessors to format UUIDs (e.g., hyphenated):

    public function getIdAttribute($value)
    {
        return Uuid::fromString($value)->toString();
    }
    
  4. Database-Specific UUID Handling Extend the package’s UuidServiceProvider to add custom logic for your database:

    public function boot()
    {
        if (config('database.default') === 'pgsql') {
            // Custom PostgreSQL logic
        }
    }
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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