PHPackages                             bnbwebexpertise/laravel-sequence - 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. bnbwebexpertise/laravel-sequence

ActivePackage

bnbwebexpertise/laravel-sequence
================================

Laravel package to handle model sequence generation (no gap)

0.0.8(7y ago)910.6k↓20%MITPHPPHP &gt;=5.6.4

Since Mar 2Pushed 7y ago6 watchersCompare

[ Source](https://github.com/bnbwebexpertise/laravel-sequence)[ Packagist](https://packagist.org/packages/bnbwebexpertise/laravel-sequence)[ RSS](/packages/bnbwebexpertise-laravel-sequence/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (1)Versions (10)Used By (0)

Laravel 5.4+ integer sequence helpers
=====================================

[](#laravel-54-integer-sequence-helpers)

This package provides helpers to work with no-gap and ordered integer sequences in Laravel models.

It has been built to help the generation of "administrative sequences" where there should be no missing value between records (invoices, etc).

**WARNING** This is *beta* version (POC). This is not yet production ready, so you should use at your own risk.

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

[](#installation)

Add the service provider to your configuration :

```
'providers' => [
        // ...

        Bnb\Laravel\Sequence\SequenceServiceProvider::class,

        // ...
],
```

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

[](#configuration)

You can customize this package behavior by publishing the configuration file :

```
php artisan vendor:publish --provider='Bnb\Laravel\Sequence\SequenceServiceProvider'

```

You can customize values without publishing by specifying those keys in your `.env` file :

```
SEQUENCE_START=123                      # defaults to 1
SEQUENCE_QUEUE_CONNECTION=database      # defaults to default
SEQUENCE_QUEUE_NAME=sequence            # defaults to default
SEQUENCE_AUTO_DISPATCH=false            # defaults to true

```

> To avoid concurrency issues when generating sequence number, the queue worker number should be set to one. It is recommended to use a dedicated queue (and worker).

Adding a sequence to a model
----------------------------

[](#adding-a-sequence-to-a-model)

Sequence columns should be generated with the following configuration in your migration :

```
$table->unsignedInteger('sequence_name')->nullable()->unique();

```

To work with sequence you must enhance your model class with the `Bnb\Laravel\Sequence\HasSequence` trait.

The `sequences` array property of your model must contain the list of the sequences names :

```
    public $sequences = ['my_sequence'];

```

Some sequence properties can be overridden by specifying a method in the model class (where `MySequence` is the name your sequence in PascalCase) :

- sequence start value (per-sequence) with the `getMySequenceStartValue() : int`
- sequence format (per-sequence) with the `formatMySequenceSequence($next, $last) : int`
- sequence generation authorization (per-sequence) with the `canGenerateMySequenceSequence() : bool`
- sequence gap filling mode (per-sequence) `isMySequenceGapFilling() : bool`
- sequence generation queue connection (for the model class) `getSequenceConnection() : string`
- sequence generation queue name (for the model class) `getSequenceQueue() : string`
- sequence auto-dispatch activation (for the model class) `isSequenceAutoDispatch() : bool`

Example :

```
use Bnb\Laravel\Sequence\HasSequence;
use Illuminate\Database\Eloquent\Model;

/**
 * MyModel model uses a sequence named
 */
class MyModel extends Model
{
    use HasSequence;

    const SEQ_INVOICE_NUMBER_START = 0;

    public $timestamps = false;

    protected $fillable = ['active'];

    protected $sequences = ['invoice_number'];

    /**
     * Assume the sequence can only be generated if active is true
     */
    protected function canGenerateReadOnlySequence()
    {
        return $this->active;
    }

    /**
     * The sequence default value must match the format
     */
    protected function getInvoiceNumberStartValue()
    {
        return sprintf('%1$04d%2$06d', date('Y'), static::SEQ_INVOICE_NUMBER_START);
    }

    /**
     * Format the sequence number with current Year that resets its counter to 0 on year change
     */
    protected function formatInvoiceNumberSequence($next, $last)
    {
        $newYear = date('Y');
        $newCounter = substr($next, 4);

        if ($last) {
            $lastYear = substr($last, 0, 4);

            if ($lastYear < $newYear) {
                $newCounter = static::SEQ_INVOICE_NUMBER_START;
            }
        }

        return sprintf('%1$04d%2$06d', $newYear, $newCounter);
    }

    /**
     * If `true`, the first number available is used, ie. the lowest number available, greater or equal to start number, including gaps caused by deletion (soft-delete included)
     * If `false` (default value), the next number will always be the last number used + 1 or the first number of the sequence when nothing pre-exists
     */
    protected function isSequenceGapFilling()
    {
        return false;
    }
}

```

### Sequence generation event

[](#sequence-generation-event)

When a sequence number is generated a model event is thrown for running custom tasks. You can listen to the sequence event using the `sequenceGenerated($sequenceName, $callback)` method (in a service provider boot method for example) :

```
    MyModel::sequenceGenerated('invoice_number', function ($model) {
        Mail::to($model->recipient_email)->send(new InvoiceGenerated($model));
    });

```

Schedule generation
-------------------

[](#schedule-generation)

You can schedule inside your console kernel the `Bnb\Laravel\Sequence\Console\Commands\UpdateSequence` at the required frequency to generate the missing sequence numbers asynchronously.

```
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('sequence:update')
                 ->hourly();
    }

```

This may not be required when using auto dispatch mode but can be used as a security fallback.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity54

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

Recently: every ~138 days

Total

8

Last Release

2632d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/08424532974ca17db79322a73bfc2a59ad82f01c98e4c9d004674afdcccce5a8?d=identicon)[gabsource](/maintainers/gabsource)

---

Top Contributors

[![gabsource](https://avatars.githubusercontent.com/u/1851314?v=4)](https://github.com/gabsource "gabsource (10 commits)")

### Embed Badge

![Health badge](/badges/bnbwebexpertise-laravel-sequence/health.svg)

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

###  Alternatives

[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11120.2M21](/packages/anourvalar-eloquent-serialize)[namu/wirechat

A Laravel Livewire messaging app for teams with private chats and group conversations.

54324.5k](/packages/namu-wirechat)[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135192.6k5](/packages/statamic-rad-pack-runway)

PHPackages © 2026

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