Laravel simplifies custom string ID implementation in your models with the refactored HasUniqueStringIds
trait. This approach preserves the framework's routing capabilities while allowing for customized identifier formats.
The basic implementation requires creating a custom trait:
trait HasSecureIdentifiers{ use HasUniqueStringIds; public function newUniqueId() { return (string) SecureId::generate(); } protected function isValidUniqueId($value): bool { return SecureId::validate($value); }}
This pattern allows for flexible implementation across different models:
class InvoiceIdentifierService{ public static function createIdentifier(): string { $prefix = config('app.env') === 'production' ? 'INV' : 'TEST'; $timestamp = now()->format('Ymd'); $random = strtoupper(Str::random(6)); return "{$prefix}-{$timestamp}-{$random}"; } public static function validateFormat(string $id): bool { $pattern = '/^(INV|TEST)-\d{8}-[A-Z0-9]{6}$/'; return preg_match($pattern, $id) === 1; }} trait HasInvoiceIdentifier{ use HasUniqueStringIds; public function newUniqueId(): string { return InvoiceIdentifierService::createIdentifier(); } protected function isValidUniqueId($value): bool { return InvoiceIdentifierService::validateFormat($value); }} class Invoice extends Model{ use HasInvoiceIdentifier; protected $keyType = 'string'; public $incrementing = false;}
The HasUniqueStringIds
trait works seamlessly with Laravel's route model binding, allowing you to maintain readable and human-friendly URLs without sacrificing functionality.