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 Auto Create Uuid Laravel Package

mindtwo/laravel-auto-create-uuid

Auto-fill a UUID v4 on Eloquent models when creating or replicating. Add a trait, add a uuid column, and it just works—no config. Supports custom UUID column names and ensures replicas get a fresh UUID by excluding the UUID attribute on replicate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require mindtwo/laravel-auto-create-uuid
    

    Ensure your project meets the requirements: PHP 8.2+ and Laravel 10-13.

  2. Add the trait to your model:

    use mindtwo\LaravelAutoCreateUuid\AutoCreateUuid;
    
    class Post extends Model
    {
        use AutoCreateUuid;
    }
    
  3. Update your migration: Add a uuid column (or your preferred name) to your table:

    $table->uuid('uuid')->unique();
    
  4. Test it: Create a new model instance—it will auto-generate a UUID:

    $post = new Post(['title' => 'Hello World']);
    $post->save(); // UUID is auto-generated
    

First Use Case

Use this package when you need consistent UUID generation for all new records without manual intervention. Ideal for APIs, distributed systems, or any application requiring globally unique identifiers.


Implementation Patterns

Core Workflow

  1. Model Creation: The trait listens to the creating event and auto-fills the UUID column if empty or invalid.

    $model = new YourModel();
    $model->save(); // UUID auto-generated
    
  2. Model Replication: Overrides replicate() to exclude the UUID column, ensuring replicas get fresh UUIDs:

    $replica = $model->replicate(); // New UUID generated
    
  3. Custom Column Names: Override the default uuid column via:

    • Property:
      protected string $uuid_column = 'custom_id';
      
    • Method:
      public function getUuidColumn(): string
      {
          return 'custom_id';
      }
      

Integration Tips

  • Mass Assignment: Ensure your $fillable array includes the UUID column if manually assigning values.
  • APIs: Useful for generating UUIDs in create endpoints without extra logic.
  • Seeding: Works seamlessly with Laravel’s seeder classes—no manual UUIDs needed.
  • Testing: Mock the trait’s fillUuidColumn() method if you need deterministic UUIDs in tests.

Advanced Patterns

  • Conditional UUIDs: Extend the trait to skip UUID generation for specific cases (e.g., bulk imports):
    use mindtwo\LaravelAutoCreateUuid\AutoCreateUuid;
    
    class ImportModel extends Model
    {
        use AutoCreateUuid;
    
        protected bool $skipUuid = false;
    
        public function setSkipUuid(bool $skip): static
        {
            $this->skipUuid = $skip;
            return $this;
        }
    
        protected function shouldGenerateUuid(): bool
        {
            return !$this->skipUuid && parent::shouldGenerateUuid();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Existing UUIDs: The trait skips generation if the column already contains a valid UUID. This can cause issues if you expect UUIDs to regenerate (e.g., during replication). Override shouldGenerateUuid() to force regeneration:

    protected function shouldGenerateUuid(): bool
    {
        return true; // Always generate, even if UUID exists
    }
    
  2. Migration Order: Ensure your UUID column is added before any foreign keys referencing it, as UUIDs are generated during model creation.

  3. Replication Edge Cases: If you manually call replicate() with $except parameters, the trait’s override may not trigger. Use:

    $replica = $model->replicate(['*']); // Force trait behavior
    

Debugging

  • UUID Validation: The trait uses Laravel’s Str::isUuid() for validation. If UUIDs appear invalid, check for:

    • Hidden whitespace or formatting issues in the database.
    • Case sensitivity (UUIDs are case-insensitive but may fail validation if malformed).
  • Event Conflicts: If other creating or replicating listeners interfere, reorder them in registerEvents():

    protected static function booted()
    {
        static::creating(function ($model) {
            // Your logic here
        });
        // Ensure AutoCreateUuid runs last
    }
    

Extension Points

  1. Custom UUID Generation: Override generateUuid() to use a different strategy (e.g., UUIDv1 for timestamps):

    protected function generateUuid(): string
    {
        return Str::orderedUuid()->toString();
    }
    
  2. Prevent Generation: Disable UUID generation for specific models by overriding shouldGenerateUuid():

    protected function shouldGenerateUuid(): bool
    {
        return false;
    }
    
  3. Post-Generation Logic: Hook into the created or replicated events to act on the new UUID:

    protected static function booted()
    {
        static::created(function ($model) {
            // Log or process the new UUID
            logger()->info('New UUID:', ['uuid' => $model->uuid]);
        });
    }
    

Performance Tips

  • Batch Inserts: For bulk inserts, disable the trait temporarily to avoid per-record UUID generation:
    $model->setAttribute('uuid', null); // Clear UUID before batch save
    
  • Caching: If UUIDs are used in high-frequency queries, consider indexing the column (already recommended in migrations).

Configuration Quirks

  • No Package Config: The package is zero-configuration—just add the trait. Avoid over-engineering setup.
  • Laravel Version: Ensure compatibility with your Laravel version (e.g., Laravel 13 may require adjustments if the package lags behind).
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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