Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Unique Code Generator Laravel Package

monurakkaya/laravel-unique-code-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require monurakkaya/laravel-unique-code-generator
    

    Publish the config file:

    php artisan vendor:publish --provider="Monurakkaya\UniqueCodeGenerator\UniqueCodeGeneratorServiceProvider"
    
  2. 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)
  3. 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();
    

Implementation Patterns

Core Workflow

  1. Model Integration:

    • Add a code column to your database table (e.g., varchar(20)).
    • Define a getUniqueCodeGeneratorConfig() method in your model:
      public function getUniqueCodeGeneratorConfig()
      {
          return [
              'prefix' => 'INV',
              'length' => 8,
          ];
      }
      
  2. Automatic Generation:

    • Use a model observer to auto-generate codes on creating:
      use Monurakkaya\UniqueCodeGenerator\Observers\UniqueCodeObserver;
      
      Invoice::observe(UniqueCodeObserver::class);
      
  3. Manual Generation:

    • Generate codes on-demand:
      $code = UniqueCodeGenerator::generate($invoice, 'custom-prefix', 10);
      
  4. Validation:

    • Ensure uniqueness via the package’s built-in checks:
      $this->validate($request, [
          'code' => 'required|unique:invoices,code',
      ]);
      

Advanced Patterns

  • 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);
    

Gotchas and Tips

Common Pitfalls

  1. Duplicate Codes:

    • Ensure your database column is indexed for performance and uniqueness.
    • If duplicates persist, check for race conditions in multi-threaded environments (e.g., queues). Use transactions:
      DB::transaction(function () use ($invoice) {
          $invoice->code = UniqueCodeGenerator::generate($invoice);
          $invoice->save();
      });
      
  2. Config Overrides:

    • Global config (config/unique-code-generator.php) takes precedence over model-specific configs unless explicitly overridden in getUniqueCodeGeneratorConfig().
  3. Case Sensitivity:

    • Default behavior is case-sensitive. For case-insensitive uniqueness, modify the query in the package’s UniqueCodeGenerator class or add a unique:table,code validation rule.
  4. Observer Conflicts:

    • If using multiple observers, ensure UniqueCodeObserver runs after other observers that might modify the model’s attributes (e.g., creating events).

Debugging Tips

  • 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!');
    }
    

Extension Points

  1. 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);
        }
    }
    
  2. 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)
    });
    
  3. Fallback Logic: Handle generation failures gracefully:

    try {
        $code = UniqueCodeGenerator::generate($invoice);
    } catch (\Exception $e) {
        $code = 'MANUAL-' . time(); // Fallback
    }
    

Performance

  • 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);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope