PHPackages                             mawuva/laravel-serial-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. mawuva/laravel-serial-sequence

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

mawuva/laravel-serial-sequence
==============================

A flexible, transactional, and extensible serial number generator for Laravel.

v1.0.5(2mo ago)16[3 PRs](https://github.com/mawuva/laravel-serial-sequence/pulls)MITPHPPHP ^8.3CI passing

Since Feb 22Pushed 2mo agoCompare

[ Source](https://github.com/mawuva/laravel-serial-sequence)[ Packagist](https://packagist.org/packages/mawuva/laravel-serial-sequence)[ Docs](https://github.com/mawuva/laravel-serial-sequence)[ GitHub Sponsors]()[ RSS](/packages/mawuva-laravel-serial-sequence/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (26)Versions (10)Used By (0)

Laravel Serial Sequence
=======================

[](#laravel-serial-sequence)

A flexible, transactional, and extensible serial number generator for Laravel.

[![Latest Version on Packagist](https://camo.githubusercontent.com/6e2f783aef817def7841ec44eec4306aa59518d0f6d88f04055b1c5e22d36908/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d61777576612f6c61726176656c2d73657269616c2d73657175656e63652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mawuva/laravel-serial-sequence)[![GitHub Tests Action Status](https://camo.githubusercontent.com/75e038d06f4a44bf685a214008896bfe010ab62e78cb6032746125d712f92852/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d61777576612f6c61726176656c2d73657269616c2d73657175656e63652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mawuva/laravel-serial-sequence/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/e49b852a523da26a42c7765b79775a10fa00b6dba38491be0ed7057db857325a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d61777576612f6c61726176656c2d73657269616c2d73657175656e63652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/mawuva/laravel-serial-sequence/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/8a848cf50ec0405f5bf67533aa0850d7bb7287e86d9ec3c8cbcb70fecf4341d9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d61777576612f6c61726176656c2d73657269616c2d73657175656e63652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mawuva/laravel-serial-sequence)

Laravel Serial Sequence provides a robust solution for generating unique serial numbers with automatic incrementation based on series, year, and month periods. Perfect for invoices, orders, tickets, and any business documents requiring sequential numbering with period-based resets.

Features
--------

[](#features)

- **Automatic serial generation** with transaction safety
- **Period-based sequences** (year/month combinations)
- **Multiple series support** for different document types
- **Powerful query scopes** for filtering and searching
- **Database-level uniqueness** guarantees
- **Optimized indexes** for performance
- **Flexible configuration** options

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

[](#installation)

You can install the package via composer:

```
composer require mawuva/laravel-serial-sequence
```

You can publish and run the migrations with:

```
php artisan vendor:publish --tag="serial-sequence-migrations"
php artisan migrate
```

You can publish the config file with:

```
php artisan vendor:publish --tag="serial-sequence-config"
```

You can publish both migrations and config with:

```
php artisan vendor:publish --tag="serial-sequence"
```

Database Setup
--------------

[](#database-setup)

### 1️. Option "Snippet / Migration Example"

[](#1️-option-snippet--migration-example)

Copy-paste this ready-to-use migration snippet into your migration file:

```
Schema::table('orders', function (Blueprint $table) {
    $table->string('serie', 10);
    $table->smallInteger('serial_year');
    $table->smallInteger('serial_month');
    $table->unsignedInteger('serial_number');
    $table->string('serial')->unique();

    // Index for business search
    $table->index(['serie', 'serial_year', 'serial_month'], 'idx_orders_serial_period');

    // Index for audit / precise search
    $table->index(['serie', 'serial_number'], 'idx_orders_serie_number');
});
```

**Advantages:**

- No magic, fully transparent
- Easy for users who just want to copy-paste
- Complete control over column names and indexes

### 2️. Option "Trait Auto Add Columns" (Recommended)

[](#2️-option-trait-auto-add-columns-recommended)

Use the built-in `HasSerialColumns` trait for cleaner migrations:

```
use Mawuva\LaravelSerialSequence\Concerns\HasSerialColumns;

Schema::table('orders', function (Blueprint $table) {
    HasSerialColumns::addSerialColumns($table, 'orders');
});
```

**Advantages:**

- ✅ Centralized definition in the package
- ✅ Easy updates and maintenance
- ✅ Consistent across all your models
- ✅ Optional index prefix for better organization

The `addSerialColumns` method automatically creates:

- `serie` (varchar(10)) - Series identifier
- `serial_year` (smallint) - Year component
- `serial_month` (smallint) - Month component
- `serial_number` (unsigned int) - Sequential number
- `serial` (varchar, unique) - Full serial string
- Optimized indexes for performance

Usage
-----

[](#usage)

### Basic Model Setup

[](#basic-model-setup)

Add the `HasSerialSequence` trait and implement the `HasSerial` contract:

```
use Illuminate\Database\Eloquent\Model;
use Mawuva\LaravelSerialSequence\Concerns\HasSerialSequence;
use Mawuva\LaravelSerialSequence\Contracts\HasSerial;

class Order extends Model implements HasSerial
{
    use HasSerialSequence;

    protected $fillable = [
        'customer_id',
        'amount',
        // serial fields are managed automatically
        'serie',
        'serial_year',
        'serial_month',
        'serial_number',
        'serial',
    ];

    protected $casts = [
        'total' => 'decimal:2',
        'serial_year' => 'integer',
        'serial_month' => 'integer',
        'serial_number' => 'integer',
    ];

    /**
     * Get the business serie identifier for orders.
     */
    public function serialSerie(): string
    {
        return 'ORD';
    }
}
```

#### Required Methods

[](#required-methods)

When implementing the `HasSerial` contract, you must define:

**`serialSerie(): string`**

- Returns the series identifier for this model type
- Maximum 10 characters
- Examples: 'ORD' for orders, 'INV' for invoices, 'TICKET' for tickets

**`setSerialAttributes(SerialData $data): void`**

- Automatically handled by the `HasSerialSequence` trait
- Populates the model's serial fields after generation
- No manual implementation needed when using the trait

#### Multiple Model Examples

[](#multiple-model-examples)

```
// Invoice model
class Invoice extends Model implements HasSerial
{
    use HasSerialSequence;

    public function serialSerie(): string
    {
        return 'INV';
    }
}

// Booking model
class Booking extends Model implements HasSerial
{
    use HasSerialSequence;

    public function serialSerie(): string
    {
        return 'BKG';
    }
}

// Ticket model
class Ticket extends Model implements HasSerial
{
    use HasSerialSequence;

    public function serialSerie(): string
    {
        return 'TICKET';
    }
}
```

### Creating Records with Serial Numbers

[](#creating-records-with-serial-numbers)

```
// Automatic serial generation
$order = Order::create([
    'customer_id' => 1,
    'amount' => 99.99,
]);

// The serial fields are automatically populated:
// - serie: 'ORD' (default or configured)
// - serial_year: 2024
// - serial_month: 2
// - serial_number: 1 (incremented)
// - serial: 'ORD-2024-02-0001'
```

### Query Scopes

[](#query-scopes)

The package provides powerful query scopes for filtering:

```
// Get orders for a specific period
$orders = Order::serialPeriod('ORD', 2024, 2)->get();

// Get orders with specific serial number in a series
$orders = Order::serialNumber('ORD', 5)->get();

// Filter by series only
$orders = Order::bySerie('ORD')->get();

// Filter by year
$orders = Order::byYear(2024)->get();

// Filter by month
$orders = Order::byMonth(2)->get();

// Range queries on serial numbers
$orders = Order::serialNumberFrom(10)->get();      // >= 10
$orders = Order::serialNumberTo(100)->get();       // byYear(2024)
    ->serialNumberFrom(50)
    ->orderBy('serial_number', 'desc')
    ->limit(10)
    ->get();

// Get the latest serial for a period
$latestOrder = Order::serialPeriod('ORD', 2024, 2)
    ->orderBy('serial_number', 'desc')
    ->first();
```

How It Works
------------

[](#how-it-works)

### Serial Number Format

[](#serial-number-format)

The package generates serial numbers in the format: `{SERIE}-{YEAR}-{MONTH}-{NUMBER}`

Example: `ORD-2024-02-0001`

- **SERIE**: Series identifier (e.g., 'ORD' for orders, 'INV' for invoices)
- **YEAR**: 4-digit year (2024)
- **MONTH**: 2-digit month (02)
- **NUMBER**: Zero-padded sequential number (0001)

### Automatic Reset

[](#automatic-reset)

Serial numbers automatically reset to 1 when:

- The series changes
- The year changes
- The month changes

This ensures clean separation between different periods and document types.

### Database Structure

[](#database-structure)

The package uses two main tables:

1. **`serial_sequences`** - Tracks the last number used for each series/period combination
2. **Your model tables** - Store the actual serial data

### Transaction Safety

[](#transaction-safety)

All serial number generation happens within database transactions to prevent:

- Duplicate serial numbers
- Gaps in sequences
- Race conditions in concurrent requests

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

[](#configuration)

### Publishing the Config File

[](#publishing-the-config-file)

Publish the configuration file to customize the serial number format:

```
php artisan vendor:publish --tag="laravel-serial-sequence-config"
```

This will create `config/serial-sequence.php` with the default settings.

### Configuration Options

[](#configuration-options)

```
