PHPackages                             cndrsdrmn/eloquent-unique-attributes - 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. [Database &amp; ORM](/categories/database)
4. /
5. cndrsdrmn/eloquent-unique-attributes

ActiveLibrary[Database &amp; ORM](/categories/database)

cndrsdrmn/eloquent-unique-attributes
====================================

A Laravel package to enforce automatic generation of unique attribute values for Eloquent models.

v0.1.0(1y ago)03201MITPHPPHP ^8.3

Since Nov 28Pushed 1y ago1 watchersCompare

[ Source](https://github.com/cndrsdrmn/eloquent-unique-attributes)[ Packagist](https://packagist.org/packages/cndrsdrmn/eloquent-unique-attributes)[ RSS](/packages/cndrsdrmn-eloquent-unique-attributes/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (1)Dependencies (7)Versions (2)Used By (1)

Eloquent Unique Attributes
==========================

[](#eloquent-unique-attributes)

[![Packagist Version](https://camo.githubusercontent.com/58b910b790f67025766b0421fe2cbfb7e42ee1b55928a541c93020e91b5c096d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636e64727364726d6e2f656c6f7175656e742d756e697175652d617474726962757465733f6c6162656c3d737461626c65)](https://packagist.org/packages/cndrsdrmn/eloquent-unique-attributes)[![GitHub Actions Workflow Status](https://camo.githubusercontent.com/55fd41a155fed63007d3f70cd7466f020ac0968af7906a2200922f89e9585cc2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636e64727364726d6e2f656c6f7175656e742d756e697175652d617474726962757465732f74657374732e796d6c3f6c6f676f3d676974687562266c6162656c3d4349)](https://github.com/cndrsdrmn/eloquent-unique-attributes/actions)[![GitHub License](https://camo.githubusercontent.com/4a6d2fa57c5036dbd3e86fb90d8839f730366bab03f78bbc8a9eed53ae957959/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f636e64727364726d6e2f656c6f7175656e742d756e697175652d61747472696275746573)](https://github.com/cndrsdrmn/eloquent-unique-attributes/blob/master/LICENSE)

A Laravel package to enforce automatic generation of unique attribute values for Eloquent models, making it easy to maintain uniqueness without manual intervention.

---

🌟 Features
----------

[](#-features)

- Automatically generate unique attribute values for Eloquent models.
- Customizable formats (`numerify`, `lexify`, or mixed patterns).
- Flexible configuration for prefixes, suffixes, separators, and retries.
- Supports models with soft deletes.
- Fully customizable events for enforcing and notifying unique attribute changes.

---

📖 Background
------------

[](#-background)

Managing unique attributes in Eloquent models often involves tedious logic, especially when combining custom formats and real-time checks. This package provides an automatic, extensible solution. It ensures attributes are unique within the database and adhere to defined configurations.

---

🛠 Installation
--------------

[](#-installation)

Install the package using Composer:

```
composer require cndrsdrmn/eloquent-unique-attributes
```

---

⚙️ Configuration
----------------

[](#️-configuration)

To customize the default behavior, publish the configuration file:

```
php artisan vendor:publish --tag=unique-attributes-config
```

This will create a `config/unique_attributes.php` file:

```
return [

    /**
     * The prefix to add to the beginning of the generated unique value.
     */
    'prefix' => '',

    /**
     * The suffix to add to the end of the generated unique value.
     */
    'suffix' => '',

    /**
     * The separator to use between prefix, value, and suffix.
     */
    'separator' => '_',

    /**
     * The maximum number of retries to generate a unique value before increasing the length.
     */
    'max_retries' => 100,

    /**
     * The default length of the generated unique value.
     */
    'length' => 8,

    /**
     * The format of the unique value.
     *
     * Supported options:
     * - `numerify` - Replace `#` with random digits.
     * - `lexify` - Replace `?` with random letters.
     * - `bothify` - Replace `#` with digits and `?` with letters.
     *
     * @see https://github.com/cndrsdrmn/php-string-formatter
     */
    'format' => 'bothify',
];
```

### Configurable Options:

[](#configurable-options)

- **`prefix`**: A string prepended to the generated value.
- **`suffix`**: A string appended to the generated value.
- **`separator`**: A separator between `prefix`, `value`, and `suffix`.
- **`max_retries`**: Maximum attempts to generate a unique value before increasing length.
- **`length`**: The initial length of the generated unique value.
- **`format`**: Determines the type of value (`numerify` for digits, `lexify` for letters, `botify` for mixed).

---

🚀 Usage
-------

[](#-usage)

### 1. Add the Trait to Your Model

[](#1-add-the-trait-to-your-model)

Include the `HasEnforcesUniqueAttributes` trait in any Eloquent model requiring unique attributes:

```
namespace App\Models;

use Cndrsdrmn\EloquentUniqueAttributes\HasEnforcesUniqueAttributes;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasEnforcesUniqueAttributes;

    /**
     * Define the unique attributes configuration.
     */
    public function enforcedUniqueColumns(): array
    {
        return [
            'barcode' => ['format' => 'numerify', 'separator' => '-'],
            'sku' => ['prefix' => 'SKU', 'length' => 10],
        ];
    }
}
```

### 2. Generate Unique Attributes

[](#2-generate-unique-attributes)

When creating the model, the unique values will automatically be enforced:

```
$product = Product::create([
    'name' => 'Sample Product',
]);

echo $product->sku; // Example: SKU_1234567890
```

---

🔧 Advanced Customization
------------------------

[](#-advanced-customization)

### Event Hooks

[](#event-hooks)

This package fires events during the unique value generation process:

- **`eloquent.enforcing`**: Fired before generating unique attributes. If a listener returns a value, the process of enforcing unique attributes is skipped.
- **`eloquent.enforced`**: After unique attributes are generated.

You can listen to these events in your application to implement custom logic:

```
use Illuminate\Support\Facades\Event;

Event::listen('eloquent.enforcing: App\Models\Product', function ($model, $event) {
    // Returning any value here will skip the enforcement of unique attributes.
    return true;
});

Event::listen('eloquent.enforced: App\Models\Product', function ($model, $status) {
    // Execute logic after unique attributes are enforced.
    if ($status) {
        Log::info('Unique attributes enforced for model', ['model' => $model]);
    }
});
```

> **Note:** If a listener for the `eloquent.enforcing` event returns a value (truthy or falsy), the unique attribute generation process will be skipped for the current model.

---

🧪 Testing
---------

[](#-testing)

This package includes PHPUnit tests. To run the tests, use the following command:

```
composer test
```

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

[](#-contributing)

We welcome contributions! Follow these steps to contribute:

1. Fork the repository.
2. Create a new branch (`git checkout -b feature-name`).
3. Commit your changes (`git commit -m "Add new feature"`).
4. Push to the branch (`git push origin feature-name`).
5. Open a Pull Request.

---

📄 License
---------

[](#-license)

This package is open-source software licensed under the [MIT license](./LICENSE).

###  Health Score

27

—

LowBetter than 47% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity44

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

Unknown

Total

1

Last Release

583d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e6241ea6ad620ee6d8fc3d3bac59afcad6c05ad00f4184da528eb44e69236789?d=identicon)[cndrsdrmn](/maintainers/cndrsdrmn)

---

Top Contributors

[![cndrsdrmn](https://avatars.githubusercontent.com/u/19147653?v=4)](https://github.com/cndrsdrmn "cndrsdrmn (3 commits)")

---

Tags

laraveleloquentattributesunique

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/cndrsdrmn-eloquent-unique-attributes/health.svg)

```
[![Health](https://phpackages.com/badges/cndrsdrmn-eloquent-unique-attributes/health.svg)](https://phpackages.com/packages/cndrsdrmn-eloquent-unique-attributes)
```

###  Alternatives

[jpkleemans/attribute-events

🔥 Fire events on attribute changes of your Eloquent model

332540.0k3](/packages/jpkleemans-attribute-events)[wendelladriel/laravel-lift

Take your Eloquent Models to the next level

70349.7k](/packages/wendelladriel-laravel-lift)[rtconner/laravel-likeable

Trait for Laravel Eloquent models to allow easy implementation of a 'like' or 'favorite' or 'remember' feature.

400396.7k5](/packages/rtconner-laravel-likeable)[poing/earmark

Laravel package to generate values in a unique and customizable series.

10713.1k](/packages/poing-earmark)[phaza/single-table-inheritance

Single Table Inheritance Trait

1515.8k](/packages/phaza-single-table-inheritance)

PHPackages © 2026

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