PHPackages                             jobsrey/laravel-autonumber - 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. jobsrey/laravel-autonumber

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

jobsrey/laravel-autonumber
==========================

2.1.0(1mo ago)015MITPHP

Since Oct 5Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/jobsrey/laravel-autonumber)[ Packagist](https://packagist.org/packages/jobsrey/laravel-autonumber)[ Docs](https://github.com/jobsrey/laravel-autonumber)[ RSS](/packages/jobsrey-laravel-autonumber/feed)WikiDiscussions master Synced 2d ago

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

Laravel AutoNumber
==================

[](#laravel-autonumber)

A Laravel package for automatically generating unique sequential numbers for your Eloquent models.

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

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.0, 11.0, 12.0, or 13.0

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

[](#installation)

Install the package via Composer:

```
composer require jobsrey/laravel-autonumber
```

### Service Provider Registration

[](#service-provider-registration)

The package uses Laravel's auto-discovery feature, so the Service Provider will be automatically registered in Laravel 5.5 and above.

For older Laravel versions or if you need manual registration, add the service provider to `config/app.php`:

```
'providers' => [
    // Other Service Providers...
    Jobsrey\AutoNumber\AutoNumberServiceProvider::class,
],
```

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

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="Jobsrey\AutoNumber\AutoNumberServiceProvider" --tag="config"
```

This will create a `config/autonumber.php` file with the following options:

```
return [
    /*
     * Autonumber format
     * '?' will be replaced with the increment number.
     */
    'format' => '?',

    /*
     * The number of digits in the autonumber
     */
    'length' => 4,

    /*
     * Whether to update the autonumber value when a model is being updated.
     * Defaults to false, which means autonumber are not updated.
     */
    'onUpdate' => false,
];
```

Migration
---------

[](#migration)

Run the migration to create the `auto_numbers` table:

```
php artisan vendor:publish --provider="Jobsrey\AutoNumber\AutoNumberServiceProvider" --tag="migrations"
php artisan migrate
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Add the `AutoNumberTrait` to your model and implement the `getAutoNumberOptions()` method:

```
use Illuminate\Database\Eloquent\Model;
use Jobsrey\AutoNumber\AutoNumberTrait;

class Invoice extends Model
{
    use AutoNumberTrait;

    protected $fillable = ['number', 'customer_id', 'amount'];

    public function getAutoNumberOptions(): array
    {
        return [
            'number' => [
                'format' => 'INV-?',  // Format: INV-0001, INV-0002, etc.
                'length' => 4,         // 4 digits with zero padding
            ],
        ];
    }
}
```

Now when you create a new Invoice, the number will be automatically generated:

```
$invoice = Invoice::create([
    'customer_id' => 1,
    'amount' => 100.00,
]);

// The number will be automatically set to: INV-0001
echo $invoice->number; // INV-0001
```

### Multiple AutoNumber Fields

[](#multiple-autonumber-fields)

You can define multiple autonumber fields for a single model:

```
class Order extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'order_number' => [
                'format' => 'ORD-?',
                'length' => 6,
            ],
            'reference' => [
                'format' => 'REF-?',
                'length' => 8,
            ],
        ];
    }
}
```

### Custom Format with Callable

[](#custom-format-with-callable)

You can use a callable for dynamic format generation:

```
class Ticket extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'ticket_number' => [
                'format' => function () {
                    $prefix = 'TICKET-' . date('Y');
                    return $prefix . '-?';
                },
                'length' => 5,
            ],
        ];
    }
}
```

### Per-Model Configuration Override

[](#per-model-configuration-override)

You can override the global configuration for specific models:

```
class Product extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'sku' => [
                'format' => 'SKU-?',
                'length' => 8,  // Override global length
            ],
        ];
    }
}
```

### Update on Model Update

[](#update-on-model-update)

By default, autonumbers are only generated when creating new models. To enable autonumber generation on updates:

1. Set `onUpdate => true` in the global config (`config/autonumber.php`)
2. Or set it per-model:

```
class Document extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'doc_number' => [
                'format' => 'DOC-?',
                'length' => 4,
                'onUpdate' => true,  // Enable update
            ],
        ];
    }
}
```

### Group Support

[](#group-support)

You can separate autonumber counters by group. This is useful when you need different sequences for different categories, branches, companies, or any other grouping criteria.

#### Static Group

[](#static-group)

Use a static string to create a fixed group:

```
class Invoice extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'number' => [
                'format' => 'INV-?',
                'length' => 4,
                'group' => 'BRANCH-001',  // Static group
            ],
        ];
    }
}
```

This will generate: `INV-0001`, `INV-0002`, etc. for BRANCH-001, and separate sequences for other branches.

#### Group from Model Field

[](#group-from-model-field)

Use a model field to create dynamic groups:

```
class Invoice extends Model
{
    use AutoNumberTrait;

    protected $fillable = ['number', 'company_id', 'amount'];

    public function getAutoNumberOptions(): array
    {
        return [
            'number' => [
                'format' => 'INV-?',
                'length' => 4,
                'group' => $this->company_id,  // Group by company
            ],
        ];
    }
}
```

Each company will have its own invoice sequence.

#### Dynamic Group with Callable

[](#dynamic-group-with-callable)

Use a callable for complex group logic:

```
class Invoice extends Model
{
    use AutoNumberTrait;

    protected $fillable = ['number', 'company_id', 'branch_id', 'amount'];

    public function getAutoNumberOptions(): array
    {
        return [
            'number' => [
                'format' => 'INV-?',
                'length' => 4,
                'group' => fn() => $this->company_id . '-' . $this->branch_id,
            ],
        ];
    }
}
```

This creates groups like `COMPANY-001-BRANCH-A`, `COMPANY-001-BRANCH-B`, etc.

#### String + Field Combination

[](#string--field-combination)

Combine static text with model fields:

```
class Invoice extends Model
{
    use AutoNumberTrait;

    protected $fillable = ['number', 'company_id', 'amount'];

    public function getAutoNumberOptions(): array
    {
        return [
            'number' => [
                'format' => 'INV-?',
                'length' => 4,
                'group' => $this->company_id . '_test',  // Company + suffix
            ],
        ];
    }
}
```

#### Backward Compatibility

[](#backward-compatibility)

Models without a `group` parameter will continue to work with a global counter:

```
class LegacyInvoice extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'number' => [
                'format' => 'INV-?',
                'length' => 4,
                // No group parameter - uses global counter
            ],
        ];
    }
}
```

#### Multiple Groups with Multiple Fields

[](#multiple-groups-with-multiple-fields)

You can use different groups for different autonumber fields:

```
class Order extends Model
{
    use AutoNumberTrait;

    public function getAutoNumberOptions(): array
    {
        return [
            'order_number' => [
                'format' => 'ORD-?',
                'length' => 6,
                'group' => $this->company_id,
            ],
            'reference' => [
                'format' => 'REF-?',
                'length' => 8,
                'group' => fn() => $this->company_id . '-' . $this->region_id,
            ],
        ];
    }
}
```

Configuration Options
---------------------

[](#configuration-options)

### format

[](#format)

The pattern for the autonumber. The `?` placeholder will be replaced with the increment number.

- Type: `string` or `callable`
- Default: `'?'`
- Example: `'INV-?'` will generate `INV-0001`, `INV-0002`, etc.

### length

[](#length)

The number of digits for zero-padding the increment number.

- Type: `int`
- Default: `4`
- Example: `4` will generate `0001`, `0002`, etc.

### onUpdate

[](#onupdate)

Whether to regenerate the autonumber when the model is updated.

- Type: `bool`
- Default: `false`
- Note: When `false`, autonumbers are only generated on model creation

### group

[](#group)

The group identifier for separating counters per group.

- Type: `string` or `callable`
- Default: `null`
- Example: `'group' => $this->company_id` or `'group' => fn() => $this->company_id . '-' . $this->branch_id`
- Note: If `null`, the counter is global per model. Each group maintains its own sequence.

License
-------

[](#license)

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

Support
-------

[](#support)

For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/jobsrey/laravel-autonumber).

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance93

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community7

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

Every ~969 days

Total

2

Last Release

34d ago

### Community

Maintainers

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

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/jobsrey-laravel-autonumber/health.svg)

```
[![Health](https://phpackages.com/badges/jobsrey-laravel-autonumber/health.svg)](https://phpackages.com/packages/jobsrey-laravel-autonumber)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k91.9k1](/packages/mike-bronner-laravel-model-caching)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[wearepixel/laravel-cart

A cart implementation for Laravel

1374.8k](/packages/wearepixel-laravel-cart)

PHPackages © 2026

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