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

stayallive/laravel-eloquent-uuid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require stayallive/laravel-eloquent-uuid
    

    Add the service provider to config/app.php (if not auto-discovered):

    'providers' => [
        // ...
        Stayallive\Laravel\Eloquent\UUID\ServiceProvider::class,
    ],
    
  2. First Use Case: Apply the UsesUUID trait to any Eloquent model:

    use Stayallive\Laravel\Eloquent\UUID\UsesUUID;
    
    class User extends Model
    {
        use UsesUUID;
    }
    

    Now, every new record will auto-generate a UUID for the primary key (id by default).


Where to Look First

  • Trait Documentation: Check the UsesUUID trait for customization options (e.g., overriding the UUID column).
  • Migration Example: The package works seamlessly with UUID-compatible database columns (e.g., uuid type in PostgreSQL or char(36) in MySQL).
  • Laravel 10 Note: While this package is functional, Laravel 10+ now includes built-in UUID/ULID support via HasUUID. Compare features if upgrading.

Implementation Patterns

Core Workflow

  1. Model Definition:

    class Post extends Model
    {
        use UsesUUID;
    
        protected $keyType = 'string'; // Required for UUIDs (default in Laravel 8+)
    }
    
    • The trait automatically casts the primary key to a string and generates UUIDs on create().
  2. Database Schema: Ensure your migration uses a UUID-compatible column:

    Schema::create('posts', function (Blueprint $table) {
        $table->uuid('id')->primary(); // PostgreSQL
        // OR
        $table->char('id', 36)->primary(); // MySQL
    });
    
  3. Querying:

    $post = Post::where('id', 'a1b2c3d4-...')->first(); // Works as expected
    

Advanced Patterns

  1. Custom UUID Column: Override the default id column:

    use Stayallive\Laravel\Eloquent\UUID\UsesUUID;
    
    class Order extends Model
    {
        use UsesUUID;
    
        protected $primaryKey = 'order_id';
    }
    
  2. Manual UUID Generation: Force a UUID for an existing model:

    $order = new Order();
    $order->forceFillUuid(); // Manually set UUID
    $order->save();
    
  3. Integration with APIs: Use UUIDs in API responses (Laravel’s default JSON casting handles strings):

    return Post::find('a1b2c3d4-...'); // Returns UUID as string
    
  4. Seeding: UUIDs work with Laravel’s seeder:

    Post::factory()->create(); // Auto-generates UUID
    

Integration Tips

  • Testing: Use HasUuid::fake() (Laravel 10+) or mock the trait’s generateUuid() method for predictable UUIDs in tests.
  • Soft Deletes: Combine with SoftDeletes trait:
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Stayallive\Laravel\Eloquent\UUID\UsesUUID;
    
    class User extends Model
    {
        use UsesUUID, SoftDeletes;
    }
    
  • Relationships: UUIDs work transparently in relationships (e.g., belongsTo, hasMany).

Gotchas and Tips

Pitfalls

  1. Database Compatibility:

    • MySQL: Use char(36) or binary(16) for UUIDs (not varchar without a fixed length).
    • SQLite: Use char(36) or text (but avoid uuid extension unless enabled).
    • Error: SQLSTATE[22007]: Invalid datetime format → Ensure your column type matches the UUID format.
  2. Primary Key Conflicts:

    • If manually setting a UUID, ensure it’s unique:
      $user = new User();
      $user->id = 'a1b2c3d4-...'; // Must be unique!
      $user->save();
      
  3. Laravel 10+ Deprecation:

    • The package is not maintained for Laravel 10+. Use Laravel’s built-in HasUUID instead:
      use Illuminate\Database\Eloquent\Concerns\HasUuid;
      
      class User extends Model
      {
          use HasUuid;
      }
      

Debugging

  1. UUID Not Generated:

    • Check if the trait is applied and $keyType = 'string' is set.
    • Verify the database column is UUID-compatible.
  2. Performance:

    • UUIDs are slightly slower than auto-increment IDs. Use ULID (via Laravel’s HasUlid) for better performance if needed.
  3. Logging: Enable query logging to debug UUID-related SQL errors:

    DB::enableQueryLog();
    $user = User::create(['name' => 'Test']);
    dd(DB::getQueryLog());
    

Extension Points

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

    protected function generateUuid()
    {
        return Str::orderedUuid(); // Laravel 10+ alternative
    }
    
  2. Event Hooks: Listen for creating events to modify UUID behavior:

    protected static function bootUsesUUID()
    {
        static::creating(function ($model) {
            if (!$model->{$model->getKeyName()}) {
                $model->{$model->getKeyName()} = Str::uuid()->toString();
            }
        });
    }
    
  3. Hybrid Keys: Combine UUIDs with other traits (e.g., HasFactory, Observables) without conflicts.


Configuration Quirks

  • No Config File: The package relies on Laravel’s default behavior. No additional configuration is needed beyond the trait.
  • Casting: Ensure your model casts the primary key to a string:
    protected $casts = [
        'id' => 'string',
    ];
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle