PHPackages                             awaresoftware/custom-id - 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. awaresoftware/custom-id

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

awaresoftware/custom-id
=======================

A Laravel package for generating unique custom IDs with configurable character sets, lengths, and prefixes

v2.0.1(1mo ago)02↓80%MITPHPPHP ^8.2

Since Jun 6Pushed 1mo agoCompare

[ Source](https://github.com/awaresoftware/custom-id)[ Packagist](https://packagist.org/packages/awaresoftware/custom-id)[ RSS](/packages/awaresoftware-custom-id/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (6)Versions (5)Used By (0)

Custom ID Generator for Laravel
===============================

[](#custom-id-generator-for-laravel)

A Laravel package for generating unique custom IDs with configurable character sets, lengths, and prefixes. Perfect for creating human-readable, collision-resistant identifiers for your Eloquent models.

Features
--------

[](#features)

- 🎲 **Configurable ID generation** - Set length, prefix, and character set per model
- 🔒 **Collision detection** - Automatic retry mechanism with configurable attempts
- 🗑️ **Soft-delete aware** - Prevents ID reuse from soft-deleted records
- 🚀 **Race condition handling** - Retries on unique constraint violations from concurrent inserts
- 🎯 **Simple API** - Just use a trait and implement one method
- 📝 **Custom exceptions** - Detailed error information for debugging
- ⚡ **Zero dependencies** - Only requires `illuminate/support`

Installation
------------

[](#installation)

```
composer require awaresoftware/custom-id
```

Quick Start
-----------

[](#quick-start)

### 1. Use the Trait

[](#1-use-the-trait)

Add the `HasCustomId` trait to your model:

```
use Aware\CustomId\Traits\HasCustomId;
use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    use HasCustomId;

    // Optional: Override if your config key differs from class name
    protected function getCustomIdType(): string
    {
        return 'event'; // Default is strtolower(class_basename(static::class))
    }

    // Optional: Provide custom configuration
    protected function getCustomIdConfig(): ?array
    {
        return [
            'length' => 6,
            'prefix' => 'EVT-',
        ];
    }
}
```

### 2. Update Your Migration

[](#2-update-your-migration)

Set the primary key as a string:

```
Schema::create('events', function (Blueprint $table) {
    $table->string('id', 10)->primary(); // Adjust length for prefix + ID length
    // ... other columns
});
```

### 3. Create Records

[](#3-create-records)

IDs are generated automatically:

```
$event = Event::create([
    'name' => 'Laravel Conference 2025',
]);

echo $event->id; // EVT-A3K7P9
```

Configuration
-------------

[](#configuration)

Publish the config file:

```
php artisan vendor:publish --tag=custom-id-config
```

Or publish everything at once (config + migration):

```
php artisan vendor:publish --tag=custom-id
```

Edit `config/custom-id.php`:

```
return [
    // Character set (removes ambiguous characters by default)
    'character_set' => 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',

    // Maximum generation attempts before throwing exception
    'max_attempts' => 10,

    // Default ID length (when not specified by model)
    'default_length' => 8,

    // Default prefix
    'default_prefix' => '',
];
```

### Per-Model Configuration

[](#per-model-configuration)

Override `getCustomIdConfig()` in your model:

```
protected function getCustomIdConfig(): ?array
{
    return [
        'length' => 8,              // ID length (excluding prefix)
        'prefix' => 'ORDER-',       // Prefix for the ID
        'character_set' => 'ABC123', // Custom character set
        'max_attempts' => 20,       // Override max retry attempts
    ];
}
```

**Or** load from your app's config:

```
// config/orders.php
return [
    'id_generation' => [
        'length' => 8,
        'prefix' => 'ORDER-',
    ],
];

// app/Models/Order.php
protected function getCustomIdConfig(): ?array
{
    return config('orders.id_generation');
}
```

Converting Users Table to Custom IDs
------------------------------------

[](#converting-users-table-to-custom-ids)

The package includes an optional migration to convert your existing `users` table from auto-incrementing integer IDs to custom string IDs.

### Publish the Migration

[](#publish-the-migration)

```
php artisan vendor:publish --tag=custom-id-users-migration
```

This will create a timestamped migration in your `database/migrations` directory.

### Configure the Migration

[](#configure-the-migration)

Before running the migration, update your `config/custom-id.php`:

```
'users' => [
    'length' => 8,          // Custom ID length for users
    'prefix' => '',         // Optional prefix (e.g., 'USR-')
],

'users_migration' => [
    'related_tables' => [
        // Add your custom tables that reference users.id
        'posts' => [
            'column' => 'user_id',
            'polymorphic' => false,
        ],
        'comments' => [
            'column' => 'author_id',
            'polymorphic' => false,
        ],
        // For polymorphic relations
        'activity_log' => [
            'column' => 'causer_id',
            'polymorphic' => true,
            'morph_type' => 'causer_type',
            'morph_value' => 'App\\Models\\User',
        ],
    ],
],
```

### Auto-Detected Tables

[](#auto-detected-tables)

The migration automatically handles these common Laravel tables:

- `sessions` (user\_id)
- `personal_access_tokens` (tokenable\_id - polymorphic)
- `notifications` (notifiable\_id - polymorphic)
- `oauth_access_tokens` (user\_id)
- `oauth_auth_codes` (user\_id)
- `oauth_clients` (user\_id)

### Run the Migration

[](#run-the-migration)

```
php artisan migrate
```

### Update Your User Model

[](#update-your-user-model)

Add the `HasCustomId` trait to your User model:

```
use Aware\CustomId\Traits\HasCustomId;

class User extends Authenticatable
{
    use HasCustomId;

    protected function getCustomIdConfig(): ?array
    {
        return config('custom-id.users');
    }
}
```

### Important Notes

[](#important-notes)

1. **Backup your database** before running this migration
2. **Test thoroughly** in a development environment first
3. The migration supports MySQL, PostgreSQL, and SQLite
4. Reverting the migration assigns new sequential integer IDs (original IDs cannot be restored)
5. Related tables configured in the config will have their columns converted to string type

Advanced Usage
--------------

[](#advanced-usage)

### Soft Delete Awareness

[](#soft-delete-awareness)

The package automatically detects if your model uses `SoftDeletes` and includes trashed records when checking for ID uniqueness:

```
use Illuminate\Database\Eloquent\SoftDeletes;

class Event extends Model
{
    use HasCustomId, SoftDeletes;

    // IDs from soft-deleted records won't be reused
}
```

### Race Condition Handling

[](#race-condition-handling)

Two-phase approach separates collision detection from race condition handling:

1. **Collision detection** — The service checks existing records (including soft-deleted) before assigning an ID
2. **Concurrent inserts** — `performInsert()` catches `UniqueConstraintViolationException` and regenerates the ID, retrying up to 3 times

```
creating event → generateCustomId() → check exists → assign ID
                                       ↓ (collision)
                                  regenerate ID

performInsert() → INSERT
                  ↓ (unique constraint violation from concurrent request)
            regenerate ID → retry INSERT (up to 3 times)

```

### Custom Exception Handling

[](#custom-exception-handling)

**Generation failures** — after exhausting all retry attempts:

```
use Aware\CustomId\Exceptions\CustomIdGenerationException;

try {
    $model = MyModel::create($data);
} catch (CustomIdGenerationException $e) {
    echo $e->modelType;  // "my_model"
    echo $e->attempts;   // 10
    echo $e->getMessage(); // "Failed to generate unique ID for my_model after 10 attempts"
}
```

**Configuration errors** — invalid config values throw `InvalidArgumentException`:

```
use InvalidArgumentException;

try {
    $model = MyModel::create($data);
} catch (InvalidArgumentException $e) {
    // "ID length must be at least 1 for [my_model], got [0]."
    // "Character set must contain at least 2 characters for [my_model]."
    // "Max attempts must be at least 1 for [my_model], got [0]."
}
```

### Using the Service Directly

[](#using-the-service-directly)

```
use Aware\CustomId\Services\IdentificationService;

$service = app(IdentificationService::class);

$id = $service->generate(
    modelType: 'product',
    existsCallback: fn($id) => Product::where('sku', $id)->exists(),
    config: [
        'length' => 6,
        'prefix' => 'SKU-',
    ]
);
```

### Using the Facade

[](#using-the-facade)

```
use Aware\CustomId\Facades\CustomId;

$id = CustomId::generate(
    'ticket',
    fn($id) => Ticket::where('code', $id)->exists(),
    ['length' => 8, 'prefix' => 'TKT-']
);
```

Character Sets
--------------

[](#character-sets)

### Default Character Set

[](#default-character-set)

```
ABCDEFGHJKLMNPQRSTUVWXYZ23456789

```

Excludes: `0`, `O`, `1`, `I`, `L` (ambiguous characters)

### Common Alternatives

[](#common-alternatives)

**Alphanumeric (uppercase):**

```
'character_set' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
```

**Alphanumeric (mixed case):**

```
'character_set' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
```

**Numbers only:**

```
'character_set' => '0123456789'
```

**Base32 (Crockford):**

```
'character_set' => '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
```

Collision Probability
---------------------

[](#collision-probability)

With default settings (31 characters, length 8):

- Total possibilities: 31^8 = ~852 billion
- At 1 million records: collision probability &lt; 0.0001%
- At 10 million records: collision probability &lt; 0.001%

Increase length for larger datasets:

- Length 6: ~887 million combinations
- Length 8: ~852 billion combinations
- Length 10: ~819 trillion combinations

Testing
-------

[](#testing)

```
composer test
```

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11.0+ or 12.0+

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) file for details.

Credits
-------

[](#credits)

Developed by [Aware j.d.o.o.](https://aware.studio)

Support
-------

[](#support)

- **Issues:** [GitHub Issues](https://github.com/aware/custom-id/issues)
- **Email:**

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance90

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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 ~18 days

Total

3

Last Release

13d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/31439089?v=4)[Aware ](/maintainers/awaresoftware)[@awaresoftware](https://github.com/awaresoftware)

---

Top Contributors

[![awaresoftware](https://avatars.githubusercontent.com/u/31439089?v=4)](https://github.com/awaresoftware "awaresoftware (15 commits)")

---

Tags

laraveluuid-alternativeid-generationcustom-id

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/awaresoftware-custom-id/health.svg)

```
[![Health](https://phpackages.com/badges/awaresoftware-custom-id/health.svg)](https://phpackages.com/packages/awaresoftware-custom-id)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[renatomarinho/laravel-page-speed

Laravel Page Speed

2.5k1.7M11](/packages/renatomarinho-laravel-page-speed)[vinkius-labs/laravel-page-speed

Laravel Page Speed

2.5k12.5k1](/packages/vinkius-labs-laravel-page-speed)[emargareten/inertia-modal

Inertia Modal is a Laravel package that lets you implement backend-driven modal dialogs for Inertia apps.

90142.9k](/packages/emargareten-inertia-modal)[wearepixel/laravel-cart

A cart implementation for Laravel

1374.8k](/packages/wearepixel-laravel-cart)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.4k](/packages/tomshaw-electricgrid)

PHPackages © 2026

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