Installation
Run composer require michalkortas/laravel-uuid in your project root.
Publish the config (if needed) with php artisan vendor:publish --provider="michalkortas\LaravelUuid\LaravelUuidServiceProvider".
Migration Modify your migration to use UUID for the primary key:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary(); // CHAR(36) in DB
// ...
});
Model Integration
Add the HasUuid trait to your Eloquent model:
use michalkortas\LaravelUuid\traits\HasUuid;
class User extends Model
{
use HasUuid;
}
First Use Case Create a record—UUIDs will auto-generate:
$user = User::create(['name' => 'John Doe']);
// $user->id is now a UUID string (e.g., "123e4567-e89b-12d3-a456-426614174000")
Auto-Generation
The trait automatically handles UUID generation on create() and save().
No manual intervention needed for new records.
Querying with UUIDs Use UUIDs in queries like any other field:
User::where('id', $uuidString)->first();
// or
User::find($uuidString); // Works due to trait's $primaryKey override
Seeding
UUIDs work seamlessly with Laravel’s DatabaseSeeder:
User::create(['name' => 'Admin']);
// UUID auto-assigned
Relationships Define relationships as usual—UUIDs are treated as primary keys:
public function posts()
{
return $this->hasMany(Post::class);
}
API Responses UUIDs serialize naturally in JSON:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "John Doe"
}
Existing Tables
For tables without UUIDs, add a uuid column and update the model’s $primaryKey:
protected $primaryKey = 'uuid';
public $incrementing = false;
Use HasUuid trait for auto-generation.
Custom UUID Generation
Override the generateUuid() method in your model:
protected function generateUuid()
{
return Str::uuid()->toString(); // Custom logic
}
Database Constraints
Ensure your database supports UUIDs (e.g., PostgreSQL, MySQL 8+ with CHAR(36)).
Migration Conflicts
$table->uuid('uuid')->nullable()->after('id');
php artisan migrate:fresh if UUIDs conflict with auto-incrementing IDs.Primary Key Overrides
$incrementing = false can cause issues with UUIDs.protected $primaryKey = 'id'; (or your UUID column name) in the model.Query Builder Quirks
Model::findOrFail($uuid) if $uuid is not a string (e.g., pass "123e4..." instead of 123e4...).Foreign Key Mismatches
uuid() in migrations:
$table->uuid('user_id')->foreign();
UUID Not Generated?
Check if the HasUuid trait is applied and the migration uses $table->uuid('id')->primary().
Verify the model’s $primaryKey matches the UUID column name.
Duplicate UUIDs?
The package uses Laravel’s Str::uuid(), which is collision-resistant. If duplicates occur, manually override generateUuid() with a deterministic logic (e.g., Ramsey\Uuid\Uuid::uuid4()).
Custom UUID Format
Override getKeyType() in your model:
public function getKeyType()
{
return 'string'; // Ensures UUIDs are treated as strings
}
UUID Validation Add validation rules for UUID fields:
use Illuminate\Validation\Rule;
$request->validate([
'id' => ['required', Rule::uuid()],
]);
UUID as Non-Primary Key Use the trait for non-primary UUID fields:
$table->uuid('external_id');
In the model:
use HasUuid;
protected $primaryKey = 'id'; // Keep auto-increment as primary
protected $uuidField = 'external_id'; // Customize trait behavior
Performance For large datasets, consider indexing UUID columns:
$table->uuid('id')->primary()->index();
How can I help you explore Laravel packages today?