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 →
Laravel Auditor Audits Your App With Your Own AI Agent image

Laravel Auditor Audits Your App With Your Own AI Agent

Read article
A simple form builder that stays out of your way image

A simple form builder that stays out of your way

Read article
Laravel AI: Trace Agent Runs With Lifecycle Events image

Laravel AI: Trace Agent Runs With Lifecycle Events

Read article
Laravel AI: Get Raw HTTP Responses and Rate Limits image

Laravel AI: Get Raw HTTP Responses and Rate Limits

Read article
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article