monurakkaya/laravel-unique-code-generator
Installation:
composer require monurakkaya/laravel-unique-code-generator
Publish the config file:
php artisan vendor:publish --provider="Monurakkaya\UniqueCodeGenerator\UniqueCodeGeneratorServiceProvider"
Configuration:
Edit config/unique-code-generator.php to define:
prefix (e.g., INV-, TICK-)length (e.g., 8 for 8-character codes)model (e.g., App\Models\Invoice)First Use Case: Generate a unique code for a model instance:
use Monurakkaya\UniqueCodeGenerator\Facades\UniqueCodeGenerator;
$invoice = new \App\Models\Invoice();
$invoice->code = UniqueCodeGenerator::generate($invoice);
$invoice->save();
Model Integration:
code column to your database table (e.g., varchar(20)).getUniqueCodeGeneratorConfig() method in your model:
public function getUniqueCodeGeneratorConfig()
{
return [
'prefix' => 'INV',
'length' => 8,
];
}
Automatic Generation:
creating:
use Monurakkaya\UniqueCodeGenerator\Observers\UniqueCodeObserver;
Invoice::observe(UniqueCodeObserver::class);
Manual Generation:
$code = UniqueCodeGenerator::generate($invoice, 'custom-prefix', 10);
Validation:
$this->validate($request, [
'code' => 'required|unique:invoices,code',
]);
Dynamic Prefixes: Use closures for dynamic prefixes (e.g., based on user roles or date ranges):
public function getUniqueCodeGeneratorConfig()
{
return [
'prefix' => function () {
return auth()->user()->role === 'admin' ? 'ADMIN-' : 'USER-';
},
'length' => 8,
];
}
Custom Storage: Override the default storage logic (e.g., cache or external API) by extending the generator:
use Monurakkaya\UniqueCodeGenerator\UniqueCodeGenerator as BaseGenerator;
class CustomUniqueCodeGenerator extends BaseGenerator
{
public function generate($model, $prefix = null, $length = null)
{
// Custom logic here
return parent::generate($model, $prefix, $length);
}
}
Bulk Generation: Generate codes for multiple models efficiently:
$codes = UniqueCodeGenerator::generateMany($invoices, 'BULK-', 6);
Duplicate Codes:
DB::transaction(function () use ($invoice) {
$invoice->code = UniqueCodeGenerator::generate($invoice);
$invoice->save();
});
Config Overrides:
config/unique-code-generator.php) takes precedence over model-specific configs unless explicitly overridden in getUniqueCodeGeneratorConfig().Case Sensitivity:
UniqueCodeGenerator class or add a unique:table,code validation rule.Observer Conflicts:
UniqueCodeObserver runs after other observers that might modify the model’s attributes (e.g., creating events).Log Generation: Enable debug mode in the config to log generated codes:
'debug' => env('UNIQUE_CODE_DEBUG', false),
Check logs for conflicts or unexpected values.
Manual Validation: Test uniqueness manually before saving:
if (static::where('code', $invoice->code)->exists()) {
throw new \Exception('Duplicate code generated!');
}
Custom Generators:
Extend the UniqueCodeGenerator class to support non-sequential logic (e.g., UUIDs, alphanumeric patterns):
class AlphanumericGenerator extends BaseGenerator
{
protected function generateCode($prefix, $length)
{
return $prefix . Str::random($length);
}
}
Event Hooks:
Listen to the unique.code.generated event for post-generation logic:
UniqueCodeGenerator::generating(function ($model, $code) {
// Modify code or model before generation
});
UniqueCodeGenerator::generated(function ($model, $code) {
// Post-generation actions (e.g., log, notify)
});
Fallback Logic: Handle generation failures gracefully:
try {
$code = UniqueCodeGenerator::generate($invoice);
} catch (\Exception $e) {
$code = 'MANUAL-' . time(); // Fallback
}
Batch Processing: For bulk inserts, generate codes in memory first, then validate uniqueness in a single query:
$codes = collect($invoices)->map(fn ($invoice) => UniqueCodeGenerator::generate($invoice));
Invoice::insert($invoices->toArray());
Caching: Cache generated codes if regeneration is expensive (e.g., API calls):
$code = cache()->remember("unique.code.{$invoice->id}", now()->addHours(1), function () use ($invoice) {
return UniqueCodeGenerator::generate($invoice);
});
How can I help you explore Laravel packages today?