monurakkaya/laravel-unique-code-generator
creating model events) for pre-generation hooks.INV-{YYYY}-{RANDOM}), making it adaptable to domain-specific requirements (e.g., ISO standards, legacy systems).UniqueCodeGenerator service into models via traits (HasUniqueCode), minimizing invasive changes. Existing models can adopt it incrementally.str_contains improvements).generateUniqueCode() method is wrapped in a transaction or lock (e.g., DB::transaction).generateUniqueCode() method.CUST-0001) that must be preserved? The package’s flexibility may need extension.Str::uuid() or database sequences.order-service generates ORDER-XXXX).Invoice) to test integration and edge cases.HasUniqueCode trait and default generator (e.g., RandomAlphaNumeric).app/Services/CustomCodeGenerator) to handle domain-specific formats.use Monurakkaya\UniqueCodeGenerator\Generators\BaseGenerator;
class InvoiceCodeGenerator extends BaseGenerator {
protected function generate(): string {
return "INV-" . date('y') . "-" . $this->randomString(6);
}
}
public static function bootHasUniqueCode() {
static::creating(function ($model) {
$attempts = 0;
do {
$model->code = $model->generateUniqueCode();
$attempts++;
} while ($model->codeExists() && $attempts < 3);
if ($attempts >= 3) {
throw new \Exception("Failed to generate unique code after 3 attempts.");
}
});
}
Str::uuid() or database sequences if generation fails.Illuminate\Support\Str (used for random string generation).creating hook syntax).random_int() (PHP 7.0+) and Str::random(). Ensure these are available.LIKE queries in uniqueness checks).config/app.php includes the package in providers.php artisan vendor:publish --provider="Monurakkaya\UniqueCodeGenerator\UniqueCodeGeneratorServiceProvider"
use Monurakkaya\UniqueCodeGenerator\Traits\HasUniqueCode;
class Invoice extends Model {
use HasUniqueCode;
protected $uniqueCodeGenerator = 'random_alphanumeric';
}
config/unique-code-generator.php.random_alphanumeric).LIKE 'PREFIX-%' queries).| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Code generation collision | Duplicate codes, data integrity | Retry logic (e.g., 3 attempts) + fallback |
How can I help you explore Laravel packages today?