PHPackages                             eg-mohamed/referenceable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. eg-mohamed/referenceable

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

eg-mohamed/referenceable
========================

Advanced Laravel package for generating customizable model reference numbers with flexible formats, sequential numbering, and comprehensive configuration options

v2.1.0(3mo ago)809.2k↓49.2%3MITPHPPHP ^8.3

Since Apr 20Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/EG-Mohamed/Referenceable)[ Packagist](https://packagist.org/packages/eg-mohamed/referenceable)[ Docs](https://github.com/eg-mohamed/referenceable)[ RSS](/packages/eg-mohamed-referenceable/feed)WikiDiscussions main Synced yesterday

READMEChangelog (8)Dependencies (24)Versions (8)Used By (0)

Referenceable
=============

[](#referenceable)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1b6844f12810aaaecbe5db96aa04f87565865ba3db252889d6db6c1d0ae05f25/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f65672d6d6f68616d65642f7265666572656e636561626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/eg-mohamed/referenceable)[![Total Downloads](https://camo.githubusercontent.com/0a779d873dfacb3337c9a55ae580b1353653f793af39e91c15e9e8c8656b9d35/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f65672d6d6f68616d65642f7265666572656e636561626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/eg-mohamed/referenceable)

An advanced Laravel package for making models referenceable with customizable reference numbers, flexible formats, sequential numbering, template-based generation, and comprehensive configuration options.

✨ Features
----------

[](#-features)

- **Multiple Generation Strategies**: Random, sequential, and template-based reference generation
- **Highly Configurable**: Extensive configuration options for prefixes, suffixes, separators, and more
- **Template System**: Use placeholders like `{YEAR}`, `{MONTH}`, `{SEQ}`, `{RANDOM}` for complex formats
- **Sequential Numbering**: Auto-incrementing sequences with reset options (daily, monthly, yearly)
- **Validation &amp; Verification**: Built-in reference validation and uniqueness checking
- **Collision Handling**: Automatic collision detection and resolution
- **Multi-Tenancy Support**: Tenant-aware reference generation
- **Artisan Commands**: Comprehensive CLI tools for management and maintenance
- **Performance Optimized**: Caching, batch processing, and database transactions
- **Laravel 10-13 Ready**: Full compatibility with the latest Laravel versions

🚀 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require eg-mohamed/referenceable
```

Install the package (creates necessary tables and publishes config):

```
php artisan referenceable:install
```

📋 Quick Start
-------------

[](#-quick-start)

### 1. Add Reference Column to Migration

[](#1-add-reference-column-to-migration)

```
Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->string('reference')->unique()->index(); // Add reference column
    $table->timestamps();
});
```

### 2. Use the Trait in Your Model

[](#2-use-the-trait-in-your-model)

```
use MohamedSaid\Referenceable\Traits\HasReference;

class Order extends Model
{
    use HasReference;

    protected $fillable = ['total', 'customer_id'];
}
```

### 3. Generate References Automatically

[](#3-generate-references-automatically)

```
$order = Order::create([
    'customer_id' => 1,
    'total' => 99.99,
]);

echo $order->reference; // Outputs: "AB12CD34" (random strategy)
```

🛠 Configuration
---------------

[](#-configuration)

### Generation Strategies

[](#generation-strategies)

Choose from three powerful generation strategies:

#### Random Strategy (Default)

[](#random-strategy-default)

```
// In your model
protected $referenceStrategy = 'random';
protected $referencePrefix = 'ORD';
protected $referenceLength = 6;
protected $referenceCase = 'upper';

// Generates: ORD-AB12CD
```

#### Sequential Strategy

[](#sequential-strategy)

```
// In your model
protected $referenceStrategy = 'sequential';
protected $referencePrefix = 'INV';
protected $referenceSequential = [
    'start' => 1000,
    'min_digits' => 6,
    'reset_frequency' => 'yearly', // never, daily, monthly, yearly
];

// Generates: INV-001000, INV-001001, INV-001002...
```

#### Template Strategy

[](#template-strategy)

```
// In your model
protected $referenceStrategy = 'template';
protected $referenceTemplate = [
    'format' => '{PREFIX}{YEAR}{MONTH}{SEQ}',
    'sequence_length' => 4,
];
protected $referencePrefix = 'ORD';

// Generates: ORD20240001, ORD20240002...
```

### Available Template Placeholders

[](#available-template-placeholders)

PlaceholderDescriptionExample`{PREFIX}`Custom prefix`ORD``{SUFFIX}`Custom suffix`2024``{YEAR}`4-digit year`2024``{YEAR2}`2-digit year`24``{MONTH}`2-digit month`03``{DAY}`2-digit day`15``{SEQ}`Sequential number`0001``{RANDOM}`Random string`AB12``{MODEL}`Model class name`Order``{TIMESTAMP}`Unix timestamp`1640995200`### Model-Level Configuration

[](#model-level-configuration)

```
class Order extends Model
{
    use HasReference;

    // Basic configuration
    protected $referenceColumn = 'order_number';     // Column name
    protected $referenceStrategy = 'template';       // random, sequential, template
    protected $referencePrefix = 'ORD';              // Prefix
    protected $referenceSuffix = '';                 // Suffix
    protected $referenceSeparator = '-';             // Separator

    // Random strategy options
    protected $referenceLength = 8;                  // Random part length
    protected $referenceCharacters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    protected $referenceExcludedCharacters = '01IOL'; // Avoid confusing chars
    protected $referenceCase = 'upper';              // upper, lower, mixed

    // Sequential strategy options
    protected $referenceSequential = [
        'start' => 1,
        'min_digits' => 6,
        'reset_frequency' => 'yearly', // never, daily, monthly, yearly
    ];

    // Template strategy options
    protected $referenceTemplate = [
        'format' => '{PREFIX}{YEAR}{MONTH}{SEQ}',
        'random_length' => 4,
        'sequence_length' => 4,
    ];

    // Validation options
    protected $referenceValidation = [
        'pattern' => '/^ORD-\d{4}-\w{6}$/', // Custom regex pattern
        'min_length' => 8,
        'max_length' => 20,
    ];

    // Advanced options
    protected $referenceUniquenessScope = 'model';   // global, model, tenant
    protected $referenceTenantColumn = 'company_id'; // For tenant-aware uniqueness
    protected $referenceCollisionStrategy = 'retry'; // retry, fail, append
    protected $referenceMaxRetries = 100;
}
```

### Global Configuration

[](#global-configuration)

Configure defaults in `config/referenceable.php`:

```
return [
    'strategy' => 'random',
    'column_name' => 'reference',

    // Random generation options
    'length' => 6,
    'prefix' => '',
    'suffix' => '',
    'separator' => '-',
    'characters' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    'excluded_characters' => '01IOL',
    'case' => 'upper',

    // Sequential generation options
    'sequential' => [
        'start' => 1,
        'min_digits' => 6,
        'reset_frequency' => 'never',
        'counter_table' => 'model_reference_counters',
    ],

    // Template generation options
    'template' => [
        'format' => '{PREFIX}{YEAR}{MONTH}{SEQ}',
        'random_length' => 4,
        'sequence_length' => 4,
    ],

    // Validation options
    'validation' => [
        'enabled' => true,
        'min_length' => 3,
        'max_length' => 50,
    ],

    // Uniqueness and collision handling
    'uniqueness_scope' => 'model', // global, model, tenant
    'collision_strategy' => 'retry',
    'max_retries' => 100,

    // Performance options
    'performance' => [
        'cache_config' => true,
        'cache_ttl' => 60,
        'use_transactions' => true,
        'batch_size' => 100,
    ],
];
```

🔧 Advanced Usage
----------------

[](#-advanced-usage)

### Manual Reference Generation

[](#manual-reference-generation)

```
// Generate without saving
$reference = $order->generateReference();

// Regenerate existing reference
$newReference = $order->regenerateReference(save: true);

// Check if model has reference
if ($order->hasReference()) {
    echo "Reference: " . $order->reference;
}
```

### Reference Validation

[](#reference-validation)

```
// Validate current reference
if ($order->validateReference()) {
    echo "Valid reference";
}

// Validate specific reference
if ($order->validateReference('ORD-123456')) {
    echo "Valid format";
}
```

### Query Scopes

[](#query-scopes)

```
// Find by reference
$order = Order::findByReference('ORD-123456');

// Models with references
$ordersWithRefs = Order::withReference()->get();

// Models without references
$ordersWithoutRefs = Order::withoutReference()->get();

// References starting with prefix
$todayOrders = Order::referenceStartsWith('ORD-2024')->get();
```

### Batch Operations

[](#batch-operations)

```
use MohamedSaid\ModelReference\ModelReference;

$modelReference = app(ModelReference::class);

// Generate multiple references
$references = $modelReference->generateBatch(Order::class, 100);

// Validate multiple references
$results = $modelReference->validateBulk($references->toArray());

// Get statistics
$stats = $modelReference->getStats(Order::class);
```

🎯 Artisan Commands
------------------

[](#-artisan-commands)

### Installation &amp; Setup

[](#installation--setup)

```
# Install package and create tables
php artisan referenceable:install

# Force reinstallation
php artisan referenceable:install --force
```

### Reference Management

[](#reference-management)

```
# Generate references for records without them
php artisan referenceable:generate "App\Models\Order"
php artisan referenceable:generate "App\Models\Order" --dry-run
php artisan referenceable:generate "App\Models\Order" --batch=500

# Validate existing references
php artisan referenceable:validate "App\Models\Order"
php artisan referenceable:validate "App\Models\Order" --fix

# Regenerate references (use with caution!)
php artisan referenceable:regenerate "App\Models\Order" --id=123
php artisan referenceable:regenerate "App\Models\Order" --all --dry-run

# Show reference statistics
php artisan referenceable:stats "App\Models\Order"
php artisan referenceable:stats "App\Models\Order" --json
```

### Package Information

[](#package-information)

```
# Show available commands
php artisan referenceable
php artisan referenceable --list
```

📊 Multi-Tenancy Support
-----------------------

[](#-multi-tenancy-support)

For multi-tenant applications:

```
class Order extends Model
{
    use HasReference;

    protected $referenceUniquenessScope = 'tenant';
    protected $referenceTenantColumn = 'company_id';

    // References will be unique per company
}
```

⚡ Performance Optimization
--------------------------

[](#-performance-optimization)

### Database Indexes

[](#database-indexes)

```
Schema::table('orders', function (Blueprint $table) {
    $table->index('reference');
    $table->index(['company_id', 'reference']); // For multi-tenant
});
```

### Configuration Caching

[](#configuration-caching)

```
// In config/referenceable.php
'performance' => [
    'cache_config' => true,  // Cache model configurations
    'cache_ttl' => 60,       // Cache for 60 minutes
    'use_transactions' => true, // Use DB transactions
    'batch_size' => 100,     // Batch size for bulk operations
],
```

🏗 Migration Guide
-----------------

[](#-migration-guide)

### From v1.x to v2.x

[](#from-v1x-to-v2x)

1. Run the installation command:

```
php artisan referenceable:install
```

2. Update your models to use new configuration format:

```
// Old format
protected $referenceLength = 8;

// New format (still supported for backward compatibility)
protected $referenceLength = 8;

// Or use new configuration array
protected $referenceTemplate = [
    'format' => '{PREFIX}{RANDOM}',
    'random_length' => 8,
];
```

3. Test your references:

```
php artisan referenceable:validate "App\Models\Order"
```

🧪 Testing
---------

[](#-testing)

```
composer test
```

📈 Changelog
-----------

[](#-changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

🤝 Contributing
--------------

[](#-contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

🔒 Security Vulnerabilities
--------------------------

[](#-security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

🏆 Credits
---------

[](#-credits)

- [Mohamed Said](https://github.com/EG-Mohamed)
- [All Contributors](../../contributors)

📄 License
---------

[](#-license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance81

Actively maintained with recent releases

Popularity39

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~56 days

Total

7

Last Release

98d ago

Major Versions

v1.0.1 → v2.0.02025-08-23

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/23424932?v=4)[Mohamed Said](/maintainers/EG-Mohamed)[@EG-Mohamed](https://github.com/EG-Mohamed)

---

Top Contributors

[![EG-Mohamed](https://avatars.githubusercontent.com/u/23424932?v=4)](https://github.com/EG-Mohamed "EG-Mohamed (25 commits)")

---

Tags

laravellaravel-packagelaravelmodel-traitsReferenceableMoSaidreference-generatorunique-identifierssequential-numbering

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/eg-mohamed-referenceable/health.svg)

```
[![Health](https://phpackages.com/badges/eg-mohamed-referenceable/health.svg)](https://phpackages.com/packages/eg-mohamed-referenceable)
```

###  Alternatives

[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

329530.5k29](/packages/codewithdennis-filament-select-tree)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

124603.0k](/packages/worksome-exchange)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[stephenjude/laravel-wallet

A simple wallet implementation for Laravel

26611.9k](/packages/stephenjude-laravel-wallet)[tarfin-labs/event-machine

Event-driven state machines for Laravel with event sourcing, type-safe context, and full audit trail.

199.4k](/packages/tarfin-labs-event-machine)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
