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.
Install the package:
composer require mindtwo/laravel-auto-create-uuid
Ensure your project meets the requirements: PHP 8.2+ and Laravel 10-13.
Add the trait to your model:
use mindtwo\LaravelAutoCreateUuid\AutoCreateUuid;
class Post extends Model
{
use AutoCreateUuid;
}
Update your migration:
Add a uuid column (or your preferred name) to your table:
$table->uuid('uuid')->unique();
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
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.
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
Model Replication:
Overrides replicate() to exclude the UUID column, ensuring replicas get fresh UUIDs:
$replica = $model->replicate(); // New UUID generated
Custom Column Names:
Override the default uuid column via:
protected string $uuid_column = 'custom_id';
public function getUuidColumn(): string
{
return 'custom_id';
}
$fillable array includes the UUID column if manually assigning values.create endpoints without extra logic.fillUuidColumn() method if you need deterministic UUIDs in tests.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();
}
}
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
}
Migration Order: Ensure your UUID column is added before any foreign keys referencing it, as UUIDs are generated during model creation.
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
UUID Validation:
The trait uses Laravel’s Str::isUuid() for validation. If UUIDs appear invalid, check for:
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
}
Custom UUID Generation:
Override generateUuid() to use a different strategy (e.g., UUIDv1 for timestamps):
protected function generateUuid(): string
{
return Str::orderedUuid()->toString();
}
Prevent Generation:
Disable UUID generation for specific models by overriding shouldGenerateUuid():
protected function shouldGenerateUuid(): bool
{
return false;
}
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]);
});
}
$model->setAttribute('uuid', null); // Clear UUID before batch save
How can I help you explore Laravel packages today?