Laravel Tutorials

Implementing Custom String Identifiers in Laravel Models

Published
Implementing Custom String Identifiers in Laravel Models image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article