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

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article
PhpStorm 2026.2 Released image

PhpStorm 2026.2 Released

Read article
Laravel Doctor: Diagnose Your App With One Artisan Command image

Laravel Doctor: Diagnose Your App With One Artisan Command

Read article
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article