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 Id Customizer Laravel Package

hexify/laravel-id-customizer

Laravel package for generating custom IDs for models or any table column. Create prefixed incremental IDs (with optional reset on prefix change) or random IDs with configurable length, character set, and extras. Use via a controller helper or a model trait.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require hexify/laravel-id-customizer
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Hexify\LaraIdCustomizer\LaraIdCustomizerServiceProvider"
    
  2. First Use Case: Generate a custom ID for a model in a controller:

    use Hexify\LaraIdCustomizer\IdCustomizer;
    
    $uid = IdCustomizer::generate([
        'model' => Student::class,
        'column' => 'uid',
        'length' => 10,
        'prefix' => 'STU'
    ]);
    

Where to Look First

  • README: Focus on the Usage section for basic syntax.
  • Config File: Check config/laravel-id-customizer.php for default settings.
  • Traits/Interfaces: Review HasIdFactory and IdFactory for model integration.

Implementation Patterns

Controller Usage

Workflow:

  1. Define ID generation config in a controller method:
    $config = [
        'model' => User::class,
        'column' => 'custom_id',
        'length' => 12,
        'prefix' => 'USER',
        'suffix' => date('Y'),
        'padding' => '0' // Optional: Pad with zeros
    ];
    
  2. Generate and assign the ID:
    $customId = IdCustomizer::generate($config);
    $user = new User(['custom_id' => $customId, ...]);
    

Integration Tips:

  • Use in store() or create() methods for consistent ID formatting.
  • Cache generated IDs if performance is critical (e.g., Redis).

Model Integration

Workflow:

  1. Implement IdFactory and use HasIdFactory in your model:
    use Hexify\LaraIdCustomizer\IdFactory;
    use Hexify\LaraIdCustomizer\Traits\HasIdFactory;
    
    class Product extends Model implements IdFactory {
        use HasIdFactory;
    
        protected $idConfig = [
            'column' => 'sku',
            'length' => 8,
            'prefix' => 'PROD',
            'suffix' => 'AUTO'
        ];
    }
    
  2. Override getCustomId() to customize logic:
    public function getCustomId(): string
    {
        return $this->generateId([
            'prefix' => 'PREMIUM_' . $this->category,
            'length' => 10
        ]);
    }
    

Common Patterns:

  • Dynamic Prefixes: Use model attributes (e.g., department) in prefix:
    'prefix' => 'DEPT_' . $this->departmentCode
    
  • Validation: Add a boot() method to validate IDs before saving:
    protected static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            if (!$model->isValidCustomId($model->{$model->getIdColumn()})) {
                throw new \Exception('Invalid ID format');
            }
        });
     }
    

Gotchas and Tips

Pitfalls

  1. Column Mismatch:

    • Ensure the column in $idConfig matches a fillable field in your model. Non-fillable fields will silently fail.
    • Fix: Add the column to $fillable:
      protected $fillable = ['id', 'custom_id', ...];
      
  2. ID Collisions:

    • If length + prefix/suffix exceeds column size (e.g., VARCHAR(10)), Laravel will truncate silently.
    • Fix: Validate column length in boot():
      static::creating(function ($model) {
          $id = $model->generateId($model->getIdConfig());
          if (strlen($id) > $model->{$model->getIdColumn() . '_length}) {
              throw new \Exception('ID exceeds column length');
          }
      });
      
  3. Trait Conflicts:

    • If your model uses another trait with boot() methods, ensure HasIdFactory runs last.
    • Fix: Reorder traits or use booted() instead of boot().

Debugging

  • Log Configs: Add debug logs to verify $idConfig:
    \Log::debug('ID Config:', $this->getIdConfig());
    
  • Test Edge Cases:
    • Test with length = 0 (should return only prefix/suffix).
    • Test with prefix/suffix longer than length (behavior may vary).

Extension Points

  1. Custom Generators:

    • Extend the IdCustomizer class to add new formats (e.g., UUID, hashed IDs):
      class CustomIdCustomizer extends IdCustomizer {
          public static function generateUuid(): string {
              return Str::uuid()->toString();
          }
      }
      
    • Register the new method in the service provider.
  2. Dynamic Configs:

    • Fetch $idConfig from a database or API:
      $this->idConfig = Setting::where('key', 'product_sku_format')->first()->value;
      
  3. Event Hooks:

    • Trigger events after ID generation:
      event(new CustomIdGenerated($this, $this->custom_id));
      

Configuration Quirks

  • Default Values: The package uses these defaults if not specified:

    [
        'length' => 10,
        'prefix' => '',
        'suffix' => '',
        'padding' => '0'
    ]
    

    Override them in config/laravel-id-customizer.php for global changes.

  • Case Sensitivity: Prefixes/suffixes are case-sensitive. Use strtoupper() if consistency is needed:

    'prefix' => strtoupper(date('ym'))
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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