PHP & Laravel
Eloquent UUID-able
Eases using and generating guid's in Laravel Eloquent models.
Requirements
- PHP
^8.3 - Laravel
^13.0
Installation
composer require kduma/eloquent-uuidable
Setup
Add the Uuidable trait to your model and create a uuid column in your migration:
use KDuma\Eloquent\Uuidable;
class User extends Model
{
use Uuidable;
}
$table->uuid('uuid')->unique();
Configuration
New style — PHP Attribute (recommended)
use KDuma\Eloquent\Uuidable;
use KDuma\Eloquent\Attributes\HasUuid;
#[HasUuid(field: 'public_uuid', checkDuplicates: true)]
class User extends Model
{
use Uuidable;
}
HasUuid parameters: field (default: 'uuid'), checkDuplicates (default: false).
Old style — model properties (deprecated)
class User extends Model
{
use Uuidable;
protected string $uuid_field = 'public_uuid'; // ⚠️ deprecated
protected bool $check_for_uuid_duplicates = true; // ⚠️ deprecated
}
Usage
- UUID is auto-generated on
createandupdateif field isnull $model->regenerateUuid()— manually regenerate (save afterwards)Model::whereUuid($uuid)— query scopeModel::byUuid($uuid)— retrieve model by UUID$model->getUuidField()— returns configured column name
Note: This package adds UUID as an additional column alongside the numeric
id, unlike Laravel's built-inHasUuidswhich replaces the primary key.
Upgrade from kduma/eloquent-guidable (1.x / 2.x)
Use #[HasUuid(field: 'guid')] to keep the old column name.