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

Referenceable Laravel Package

eg-mohamed/referenceable

Laravel package that adds reference numbers to Eloquent models with configurable formats. Supports random, sequential, and template-based generation (e.g., year/month/seq/random), collision handling, validation, and tenant-aware sequences. Includes install command, config publishing, and Laravel 10–...

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require eg-mohamed/referenceable
    php artisan referenceable:install
    
  2. Add reference column to your migration:
    Schema::create('orders', function (Blueprint $table) {
        $table->string('reference')->unique()->index();
        // ...
    });
    
  3. Apply trait to your model:
    use MohamedSaid\Referenceable\Traits\HasReference;
    
    class Order extends Model
    {
        use HasReference;
    }
    
  4. First use case: Create a record and auto-generate a reference:
    $order = Order::create(['customer_id' => 1]);
    echo $order->reference; // e.g., "ORD-123456"
    

Where to Look First

  • Model Configuration: Focus on protected $referenceStrategy (random, sequential, template) and its corresponding options.
  • Artisan Commands: Use php artisan referenceable to explore available commands.
  • Template Placeholders: Reference the {PREFIX}, {SEQ}, {YEAR}, etc., for template-based generation.

Implementation Patterns

Core Workflows

  1. Model Integration:

    • Default Strategy: Use protected $referenceStrategy = 'random' for simple alphanumeric references.
    • Sequential Strategy: Ideal for ordered records (e.g., invoices):
      protected $referenceStrategy = 'sequential';
      protected $referenceSequential = [
          'start' => 1000,
          'reset_frequency' => 'monthly',
      ];
      
    • Template Strategy: Combine placeholders for complex formats:
      protected $referenceStrategy = 'template';
      protected $referenceTemplate = [
          'format' => '{PREFIX}{YEAR}{SEQ}',
          'sequence_length' => 4,
      ];
      
  2. Batch Operations:

    • Generate references for existing records:
      php artisan referenceable:generate App\Models\Order --batch=500
      
    • Validate or regenerate references:
      php artisan referenceable:validate App\Models\Order --fix
      
  3. Querying:

    • Use scopes for filtering:
      $orders = Order::referenceStartsWith('ORD-2024')->get();
      $order = Order::findByReference('ORD-123456');
      
  4. Multi-Tenancy:

    • Configure tenant-aware uniqueness:
      protected $referenceUniquenessScope = 'tenant';
      protected $referenceTenantColumn = 'company_id';
      

Integration Tips

  • Migrations: Always add an index to the reference column for performance:
    Schema::table('orders', function (Blueprint $table) {
        $table->index('reference');
    });
    
  • Validation: Extend Laravel’s validation rules:
    use MohamedSaid\Referenceable\Rules\ValidReference;
    
    $request->validate([
        'reference' => ['required', new ValidReference(Order::class)],
    ]);
    
  • Events: Listen for reference generation:
    Order::created(function ($order) {
        logger()->info("Generated reference: {$order->reference}");
    });
    

Gotchas and Tips

Pitfalls

  1. Collision Handling:

    • Default retry strategy may cause delays if references are highly constrained. Monitor referenceMaxRetries and consider append for high-volume systems.
    • Fix: Increase referenceMaxRetries or switch to append in config/referenceable.php:
      'collision_strategy' => 'append',
      
  2. Sequential Resets:

    • reset_frequency (e.g., monthly) resets counters at midnight. Test edge cases (e.g., records created at 23:59 vs 00:01).
    • Fix: Use never for global sequences or adjust start values to avoid overlaps.
  3. Template Placeholders:

    • {SEQ} in template strategy shares the same counter as sequential strategy. Overlaps can occur if both are used.
    • Fix: Use distinct counter tables or disable sequential strategy if using templates.
  4. Performance:

    • Bulk operations (generateBatch) may lock tables. Use --batch to control concurrency.
    • Fix: Set batch_size in config/referenceable.php:
      'batch_size' => 100,
      
  5. Caching:

    • cache_config improves performance but may cause stale configurations during deployments.
    • Fix: Clear cache after config changes:
      php artisan config:clear
      

Debugging

  • Artisan Commands:
    • Use --dry-run to preview changes:
      php artisan referenceable:generate App\Models\Order --dry-run
      
    • Check stats for issues:
      php artisan referenceable:stats App\Models\Order --json
      
  • Logs:
    • Enable debug mode in config/referenceable.php:
      'debug' => env('APP_DEBUG', false),
      
    • Check Laravel logs for collision errors or generation failures.

Extension Points

  1. Custom Strategies:

    • Extend MohamedSaid\Referenceable\Strategies\StrategyInterface to create custom generators (e.g., UUID-based or hash-based).
    • Register the strategy in config/referenceable.php:
      'strategies' => [
          'custom' => \App\Strategies\CustomReferenceStrategy::class,
      ],
      
  2. Dynamic Configuration:

    • Override configuration dynamically via accessors:
      public function getReferencePrefixAttribute()
      {
          return $this->isPremium() ? 'PREM-' : 'ORD-';
      }
      
  3. Validation Rules:

    • Extend ValidReference rule for custom logic:
      use MohamedSaid\Referenceable\Rules\ValidReference as BaseValidReference;
      
      class CustomValidReference extends BaseValidReference
      {
          public function passes($attribute, $value)
          {
              return parent::passes($attribute, $value) &&
                     str_contains($value, 'VALID');
          }
      }
      
  4. Counter Management:

    • Manually reset counters via the ModelReference service:
      $modelReference = app(\MohamedSaid\Referenceable\ModelReference::class);
      $modelReference->resetCounter(Order::class);
      

Configuration Quirks

  • Global vs. Model Config:
    • Model-level settings override global config. Use config('referenceable.strategy') to check defaults.
  • Case Sensitivity:
    • referenceCase affects output but not uniqueness checks. Ensure case-insensitive indexes if needed:
      Schema::table('orders', function (Blueprint $table) {
          $table->index('reference', 'idx_reference_lower');
      });
      
  • Character Sets:
    • Custom referenceCharacters may break validation patterns. Test thoroughly with edge cases (e.g., special characters).
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.
milito/query-filter
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