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 Steps

  1. Installation:

    composer require eg-mohamed/referenceable
    php artisan referenceable:install
    
    • Publishes config, migrations, and creates necessary tables.
  2. Add Column to Migration:

    Schema::create('orders', function (Blueprint $table) {
        $table->string('reference')->unique()->index();
        // ...
    });
    
  3. Apply Trait to Model:

    use MohamedSaid\Referenceable\Traits\HasReference;
    
    class Order extends Model {
        use HasReference;
    }
    
  4. First Use Case:

    $order = Order::create(['customer_id' => 1]);
    echo $order->reference; // Auto-generated (e.g., "ORD-123456")
    

Where to Look First

  • Config: config/referenceable.php for global defaults.
  • Model Trait: HasReference for model-specific overrides.
  • Artisan Commands: php artisan referenceable --list for CLI tools.

Implementation Patterns

Core Workflows

  1. Automatic Generation:

    // Model saves with reference automatically
    $invoice = Invoice::create(['amount' => 100]);
    
  2. Manual Generation:

    $ticket = new SupportTicket();
    $ticket->generateReference(); // Force generation
    $ticket->save();
    
  3. Batch Processing:

    // CLI: Generate references for 1,000 existing records
    php artisan referenceable:generate App\Models\Order --batch=500
    

Integration Tips

  • Validation:

    // Form request validation
    $request->validate([
        'reference' => 'required|reference_format:ORD-\d{6}'
    ]);
    
  • Query Scopes:

    // Find by reference
    $order = Order::findByReference('ORD-123456');
    
    // Filter by prefix
    $todayOrders = Order::referenceStartsWith('ORD-2024')->get();
    
  • Multi-Tenancy:

    class Order extends Model {
        use HasReference;
    
        protected $referenceUniquenessScope = 'tenant';
        protected $referenceTenantColumn = 'company_id';
    }
    

Template-Based Patterns

// Dynamic references with placeholders
protected $referenceTemplate = [
    'format' => '{PREFIX}{YEAR}{SEQ}',
    'sequence_length' => 4,
];
  • Use Case: Invoices with yearly sequences (INV20240001).

Gotchas and Tips

Pitfalls

  1. Collision Handling:

    • Default: retry (auto-retry on collision).
    • Set collision_strategy: fail to throw exceptions for debugging.
    • Monitor max_retries (default: 100) to avoid infinite loops.
  2. Sequential Reset:

    • reset_frequency: yearly resets counters at year start.
    • Gotcha: Test with php artisan referenceable:stats to verify reset logic.
  3. Performance:

    • Disable use_transactions for bulk operations if ACID isn’t critical.
    • Cache config with 'cache_config': true for high-traffic models.

Debugging

  • Validate References:
    php artisan referenceable:validate App\Models\Order --fix
    
  • Check Stats:
    php artisan referenceable:stats App\Models\Order --json
    

Extension Points

  1. Custom Strategies:

    // Extend the generator
    class CustomStrategy extends \MohamedSaid\Referenceable\Strategies\BaseStrategy {
        public function generate() { ... }
    }
    

    Register in config/referenceable.php:

    'strategies' => [
        'custom' => \App\Strategies\CustomStrategy::class,
    ],
    
  2. Placeholder Extensions: Override getTemplatePlaceholders() in your model to add custom placeholders (e.g., {CUSTOM}).

  3. Event Hooks: Listen for referenceable.generated or referenceable.collision events:

    Event::listen('referenceable.generated', function ($model, $reference) {
        // Log or notify
    });
    

Config Quirks

  • Backward Compatibility: Old properties (e.g., $referenceLength) still work but prefer the new array format:

    // Old (still supported)
    protected $referenceLength = 8;
    
    // New (recommended)
    protected $referenceTemplate = ['random_length' => 8];
    
  • Global vs. Model Overrides: Model properties override global config. Use php artisan referenceable:stats to verify active settings.

Performance Tips

  • Indexing: Add indexes to reference columns and tenant columns (if multi-tenant):

    Schema::table('orders', function (Blueprint $table) {
        $table->index('reference');
        $table->index(['company_id', 'reference']);
    });
    
  • Batch Size: Adjust 'batch_size': 1000 in config/referenceable.php for bulk operations.

  • Caching: Enable 'cache_config': true to cache model configurations (reduces DB lookups).

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor