Skip to content

Getting Started

Install via Composer:

Terminal window
composer require cline/strongly-typed-id

Strongly Typed ID provides type-safe identifier value objects for PHP applications. Instead of passing raw strings or integers as IDs, you get compile-time type safety that prevents mixing IDs across different entity types.

  • Type Safety: Distinct ID types prevent accidental mixing (e.g., UserId vs OrderId)
  • Immutability: All IDs are readonly value objects
  • Multiple Formats: UUID (all versions), ULID, NanoID, GUID, Sqid, Hashids
  • Laravel Integration: Eloquent casts, Spatie Laravel Data support
  • DDD-Friendly: Perfect for domain-driven design aggregates

Create strongly-typed IDs by extending the base class:

use Cline\StronglyTypedId\ValueObjects\StronglyTypedId;
final readonly class UserId extends StronglyTypedId {}
final readonly class OrderId extends StronglyTypedId {}
final readonly class ProductId extends StronglyTypedId {}
$userId = UserId::generate();
// e.g., "018c5d6e-5f89-7a9b-9c1d-2e3f4a5b6c7d" (UUID v7 by default)
$userId = UserId::fromString('550e8400-e29b-41d4-a716-446655440000');
function findUser(UserId $id): User
{
// Implementation
}
$userId = UserId::generate();
$orderId = OrderId::generate();
findUser($userId); // ✓ Valid
findUser($orderId); // ✗ Type error: Expected UserId, got OrderId

Publish the configuration file:

Terminal window
php artisan vendor:publish --tag=strongly-typed-id-config

Configure your preferred ID generator in config/strongly-typed-id.php:

return [
// Default generator: uuid_v1, uuid_v3, uuid_v4, uuid_v5, uuid_v6, uuid_v7, uuid_v8, ulid
'generator' => env('STRONGLY_TYPED_ID_GENERATOR', 'uuid_v7'),
];

Or set it programmatically:

use Cline\StronglyTypedId\Enums\GeneratorType;
use Cline\StronglyTypedId\Facades\IdGenerator;
IdGenerator::setGenerator(GeneratorType::UuidV7);
FormatLengthSortableBest For
UUID v736 charsYesDatabase PKs (recommended)
UUID v436 charsNoRandom IDs, legacy systems
ULID26 charsYesCompact sortable IDs
NanoID21 charsNoURL-safe short IDs
SqidVariableNoObfuscated integer encoding
HashidVariableNoReversible integer encoding