Installation:
composer require dyrynda/laravel-model-uuid
Publish the config (optional):
php artisan vendor:publish --provider="Dyrynda\\ModelUuid\\ModelUuidServiceProvider" --tag="config"
Enable UUIDs for a Model:
Use the HasUuid trait in your Eloquent model:
use Dyrynda\\ModelUuid\\Traits\\HasUuid;
class User extends Model
{
use HasUuid;
}
First Use Case:
uuid type (e.g., uuid() in Laravel migrations).UUID Generation:
create() if id is not set.getUuid() method override:
public function getUuid()
{
return Str::uuid()->toString(); // Custom logic
}
Querying with UUIDs:
$user = User::where('uuid', $uuid)->first();
Relationships:
public function posts()
{
return $this->hasMany(Post::class);
}
API Responses:
toArray() or toJson() if customization is required.Database Schema:
Use uuid() in migrations (Laravel 8+):
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
// ...
});
For older Laravel versions, use string(36) and cast to UUID in the model.
Seeding: UUIDs are auto-generated, but you can manually set them in seeders:
User::create(['uuid' => Str::uuid(), 'name' => 'Test']);
Testing: Mock UUID generation in tests:
$this->partialMock(User::class, function ($mock) {
$mock->shouldReceive('getUuid')->andReturn('test-uuid');
});
Database Compatibility:
char(36) and cast to UUID in the model:
protected $casts = ['uuid' => 'string'];
Primary Key Conflicts:
id is not nullable, ensure UUIDs are generated before saving:
$user = new User();
$user->forceFill(['uuid' => Str::uuid()]);
$user->save();
Soft Deletes:
deleted_at column is not a UUID.Caching:
uuid() in cache keys if needed:
Cache::put("user_{$user->uuid}", $data, $minutes);
UUID Not Generated:
Check if HasUuid trait is applied and uuid column exists in the database.
Verify no custom getIncrementing() or getKeyType() overrides conflict.
Query Issues:
Use toSql() on queries to debug UUID filtering:
\Log::info(User::where('uuid', $uuid)->toSql());
Custom UUID Generation:
Override getUuid() or use a custom generator:
use Ramsey\Uuid\Uuid;
public function getUuid()
{
return Uuid::uuid4()->toString();
}
UUID Validation:
Add validation rules in rules() or validate():
use Dyrynda\\ModelUuid\\Rules\\Uuid;
$request->validate([
'uuid' => ['required', new Uuid],
]);
UUID Formatting: Customize UUID output (e.g., hyphenated vs. non-hyphenated):
public function getAttribute($key)
{
if ($key === 'uuid') {
return str_replace('-', '', parent::getAttribute($key));
}
return parent::getAttribute($key);
}
UUID as Foreign Key:
Use uuid() for foreign keys in migrations and define relationships normally:
public function owner()
{
return $this->belongsTo(User::class, 'owner_id', 'uuid');
}
How can I help you explore Laravel packages today?