goldspecdigital/laravel-eloquent-uuid
Installation:
composer require goldspecdigital/laravel-eloquent-uuid
Run migrations (if using the default uuid column type):
php artisan migrate
Configure Models:
Extend your Eloquent models with HasUUID trait:
use GoldspecDigital\LaravelEloquentUuid\HasUUID;
class User extends Model
{
use HasUUID;
}
First Use Case:
Create a new model instance:
$user = User::create(['name' => 'John Doe']);
The id will now be a UUID (e.g., 123e4567-e89b-12d3-a456-426614174000).
Query by UUID:
$user = User::find('123e4567-e89b-12d3-a456-426614174000');
config/eloquent-uuid.php: Customize UUID generation (e.g., version, namespace).app/Models/YourModel.php: Ensure HasUUID is used.uuid for PostgreSQL, char(36) for MySQL).Model Integration:
HasUUID to all models requiring UUIDs.uuid in $fillable if needed (though UUIDs are auto-generated):
protected $fillable = ['name', 'email']; // UUID is auto-generated
UUID Generation:
Ramsey\Uuid\Uuid::uuid4() (random UUID).getIncrementing() and getKeyType():
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'string';
}
Database Schema:
uuid column type.char(36) or binary(16).char(36) (no native UUID support).Relationships:
// Migration for posts table
Schema::create('posts', function (Blueprint $table) {
$table->uuid('user_id')->constrained()->onDelete('cascade');
// ...
});
APIs and Serialization:
public function toArray($request)
{
return [
'id' => $this->id, // UUID string
'name' => $this->name,
];
}
Seeding:
Str::uuid() or Ramsey\Uuid\Uuid::uuid4() in seeders:
$user = User::create([
'name' => 'Test User',
'uuid' => Str::uuid(), // Optional: manually set UUID
]);
Existing Projects:
// Example migration
Schema::table('users', function (Blueprint $table) {
$table->uuid('id')->default(DB::raw('(SELECT uuid_generate_v4())));
$table->dropPrimary(['id']);
$table->primary('id');
});
Testing:
HasFactory with UUIDs:
public function defineModelFactory()
{
return UserFactory::new()->state([
'uuid' => Str::uuid(),
]);
}
Caching:
cache()->put("user:{$user->id}", $user)).Foreign Key Constraints:
uuid in PostgreSQL, char(36) in MySQL).SQLSTATE[23000]: Integrity constraint violation: 1235 Column count doesn't match value count (mismatched column types).Auto-Increment Conflicts:
incrementing = true (default), UUIDs will be ignored. Always set:
public function getIncrementing()
{
return false;
}
UUID Length in MySQL:
char(36) for UUIDs in MySQL may cause issues with indexing or storage. Consider binary(16) for better performance:
$table->binary('id')->as('uuid')->primary();
Case Sensitivity:
// Avoid case mismatches
$user = User::where('id', strtolower($uuid))->first();
Legacy Code:
User::find(1)). Update all queries to handle UUIDs:
// Old (breaks)
$user = User::find(1);
// New
$user = User::find('123e4567-e89b-12d3-a456-426614174000');
UUID Generation in Tests:
Str::uuid():
// Bad: Hardcoded UUID
$user = User::find('123e4567-e89b-12d3-a456-426614174000');
// Good: Dynamic UUID
$user = User::factory()->create();
Query Issues:
php artisan schema:dump
php artisan db:show users
Performance:
uuid-ossp extension for faster generation.binary(16) instead of char(36).Package Conflicts:
webpatser/laravel-uuid), remove them to avoid conflicts:
composer remove webpatser/laravel-uuid
Custom UUID Generation:
bootHasUUID() method in your model:
protected static function bootHasUUID()
{
static::creating(function ($model) {
$model->uuid = Str::orderedUuid(); // Custom logic
});
}
UUID Versioning:
config/eloquent-uuid.php:
'version' => 1, // Use UUIDv1 (time-based)
UUID Namespaces:
'namespace' => '123e4567-e89b-12d3-a456-426614174000', // Your namespace UUID
Hybrid Keys:
public function getRouteKeyName()
{
return ['tenant_id', 'uuid'];
}
UUID Casting:
protected $casts = [
'id' => 'string',
];
UUID Shortening:
ramsey/uuid to shorten UUIDs for URLs (e.g., base64 encoding):
use Ramsey\Uuid\Uuid;
$shortUuid = base64_encode(Uuid::uuid4()->getBytes());
Bulk Operations:
insert and update statements:
User::insert([
['name' => 'User 1', 'uuid' => Str::uuid()],
['name' => 'User 2', 'uuid
How can I help you explore Laravel packages today?