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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article