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

simlux/laravel-model-uuid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require simlux/laravel-model-uuid:dev-master
    

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

    Simlux\LaravelModelUuid\LaravelModelUuidServiceProvider::class,
    
  2. First Use Case:

    • Add UuidModelTrait to a model:
      use Simlux\LaravelModelUuid\Uuid\UuidModelTrait;
      
      class MyModel extends Model
      {
          use UuidModelTrait;
      }
      
    • Run a migration with UuidMigrationHelper to add the uuid column and unique index:
      use Simlux\LaravelModelUuid\Migration\UuidMigrationHelper;
      
      Schema::create('my_models', function (Blueprint $table) {
          $table->unsignedBigInteger('id', true); // Auto-incrementing ID
          UuidMigrationHelper::uuid($table);      // Adds UUID column + unique index
      });
      
  3. First Query:

    // Create a record with auto-generated UUID
    $model = MyModel::create(['name' => 'Test']);
    
    // Find by UUID
    $model = MyModel::uuid($model->uuid)->first();
    
    // Find by UUID (alternative syntax)
    $model = MyModel::where('uuid', $model->uuid)->first();
    

Implementation Patterns

Common Workflows

  1. Model Setup:

    • Use UuidModelTrait in all models requiring UUIDs. No additional configuration is needed beyond the trait and migration helper.
    • Example:
      class User extends Model
      {
          use UuidModelTrait;
      
          protected $fillable = ['name', 'email'];
      }
      
  2. Migrations:

    • Always include UuidMigrationHelper::uuid($table) in your up() method for new tables.
    • For existing tables, manually add:
      $table->string('uuid')->unique();
      
      and update the model to use the trait.
  3. Querying:

    • Leverage the uuid() scope for cleaner queries:
      // Get a model by UUID
      $user = User::uuid($request->uuid)->firstOrFail();
      
      // Get multiple models by UUIDs
      $users = User::whereIn('uuid', $uuidArray)->get();
      
  4. Seeding:

    • Use Str::uuid() to generate UUIDs in seeders:
      User::create([
          'uuid' => Str::uuid(),
          'name' => 'Admin',
      ]);
      
  5. APIs and Serialization:

    • Expose UUIDs in API responses by default (Laravel's default JSON serialization includes all attributes, including uuid).
    • Example response:
      {
          "id": 1,
          "uuid": "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv",
          "name": "Test"
      }
      
  6. Relationships:

    • Use UUIDs as foreign keys in polymorphic or non-standard relationships:
      class Post extends Model
      {
          use UuidModelTrait;
      
          public function author()
          {
              return $this->belongsTo(User::class, 'author_uuid', 'uuid');
          }
      }
      
  7. Testing:

    • Generate predictable UUIDs for tests:
      $uuid = '00000000-1111-2222-3333-444444444444';
      $model = MyModel::uuid($uuid)->create(['name' => 'Test']);
      

Gotchas and Tips

Pitfalls

  1. Auto-Incrementing ID vs. UUID:

    • The package assumes you still want an auto-incrementing id column (as shown in the migration example). If you only want UUIDs, remove the id column and update the model to use public $incrementing = false;.
    • Example for UUID-only:
      class MyModel extends Model
      {
          use UuidModelTrait;
      
          public $incrementing = false;
          protected $keyType = 'string';
          protected $primaryKey = 'uuid';
      }
      
  2. Unique Index Conflicts:

    • If you manually add a uuid column without the unique index, the package will not automatically add it. Always use UuidMigrationHelper::uuid($table) for consistency.
    • For existing tables, run:
      Schema::table('my_models', function (Blueprint $table) {
          $table->string('uuid')->unique()->change();
      });
      
  3. Case Sensitivity:

    • UUIDs are case-sensitive in some databases (e.g., PostgreSQL). Ensure consistency when querying:
      // Use strtolower/strtoupper if needed
      $model = MyModel::where('uuid', strtolower($uuid))->first();
      
  4. Hybrid Primary Keys:

    • If you switch from id to uuid as the primary key, update your model:
      protected $primaryKey = 'uuid';
      public $incrementing = false;
      protected $keyType = 'string';
      
    • Run php artisan cache:clear and php artisan config:clear after changes.
  5. Soft Deletes:

    • If using SoftDeletes, ensure the UUID is included in queries:
      $model = MyModel::withTrashed()->uuid($uuid)->first();
      

Debugging

  1. Missing UUID Column:

    • If uuid() queries fail, verify the column exists in the database and is named uuid.
    • Check for typos in the migration or table name.
  2. UUID Generation Issues:

    • If UUIDs are not generated, ensure:
      • The uuid column is not set to nullable.
      • The UuidModelTrait is properly used in the model.
      • No custom boot() method is overriding the UUID logic.
  3. Performance:

    • UUIDs are longer than integers, which can impact indexing and joins. Monitor query performance in production, especially for large datasets.

Extension Points

  1. Custom UUID Generation:

    • Override the default UUID generation by adding a boot() method to your model:
      protected static function boot()
      {
          parent::boot();
          static::creating(function ($model) {
              $model->uuid = Str::orderedUuid(); // Use a custom UUID generator
          });
      }
      
  2. UUID Formatting:

    • Modify how UUIDs are stored or retrieved by overriding the getUuidAttribute or setUuidAttribute methods:
      public function getUuidAttribute($value)
      {
          return strtoupper($value); // Store/retrieve UUIDs in uppercase
      }
      
  3. Custom Migration Helper:

    • Extend UuidMigrationHelper to add options (e.g., length, index name):
      UuidMigrationHelper::uuid($table, [
          'length' => 36,
          'indexName' => 'custom_uuid_index',
      ]);
      
  4. UUID as Foreign Key:

    • Create a custom trait to handle UUID foreign keys:
      trait UuidForeignKey
      {
          public function setForeignKey($key)
          {
              $this->foreignKey = $key . '_uuid';
          }
      }
      
      Usage:
      class Post extends Model
      {
          use UuidForeignKey;
      
          public function author()
          {
              return $this->belongsTo(User::class);
          }
      }
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky