# rajeshmk/laravel-sequence architecture

> Architecture diagram of the GitHub repository rajeshmk/laravel-sequence, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-14). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/rajeshmk/laravel-sequence
- Repository: https://github.com/rajeshmk/laravel-sequence

## Overview

1. **What this repository is**
   - A Laravel package that generates concurrency-safe, human-readable sequence numbers.
   - It is not an app; it is a reusable library centered on one persistence-backed counter service.

2. **Primary runtime boundary**
   - The package is built around a hard requirement: sequence generation must happen inside a database transaction.
   - Correctness depends on row-level locking (`SELECT ... FOR UPDATE`) against a `sequences` table, so the key architectural boundary is “caller-owned transaction + package-managed counter row.”

3. **Core sequence flow**
   - Consumers call the `sequence('name')` helper.
   - That returns a fluent `NextSequence` builder, which collects options like prefix, padding, range, grouping, and formatting.
   - When `next()` is called, the builder resolves the active connection, locks the matching counter row, increments `last_number`, formats the result, and returns the final string.

4. **Persistence model**
   - The state lives in a `sequences` table created by the package migration.
   - Each counter is keyed by a `(name, group_by)` tuple, with `last_number` holding the current numeric position.
   - This means grouping is not just display logic; it determines which counter row is used and when numbering resets.

5. **Configuration subsystem**
   - `config/sequence.php` controls package-wide behavior such as table name, database connection, model class, and strict validation mode.
   - `SequenceConfig` is the internal configuration object used by both the fluent API and Eloquent trait integration.
   - It also owns policy choices like min/max ranges, overflow behavior, pad length, prefix, and format template/callback handling.

6. **Eloquent model integration**
   - The `HasSequence` trait lets application models auto-assign sequence values during the `creating` lifecycle event.
   - A model defines `sequenceColumns()`, returning a `SequenceColumnCollection` that maps model columns to per-column `SequenceConfig`.
   - This path still depends on a transaction; the trait does not replace the concurrency model, it just automates when the sequence is reserved.

7. **Grouping and scope rules**
   - The package supports grouping by raw values, date-based helpers, or persisted Eloquent models.
   - Helpers like `groupByYear()`, `groupByMonth()`, `groupByDay()`, and `belongsTo()` affect the storage key, not the rendered output.
   - If the group token should also appear in the final number, the caller must include it in the prefix or format string.

8. **Formatting and number policy**
   - `prefix()`, `padLength()`, and `format()` shape the returned string only after the numeric counter is reserved.
   - Range controls (`range()`, `bounded()`, `cyclingRange()`, `cycle()`, `throwOnOverflow()`) govern numeric limits and overflow behavior.
   - Overflow is explicit and typed, with failure or cycling behavior chosen by configuration.

9. **Error and event boundaries**
   - The library has a dedicated exception hierarchy for invalid config, invalid models, missing transactions, validation failures, and overflow.
   - It also emits a `SequenceAssigned` event whenever a value is reserved, carrying the internal name, raw number, final sequence string, and group key.
   - That makes reservation observable without coupling business code to the persistence implementation.

10. **Package wiring**
    - `SequenceServiceProvider` is the integration point for Laravel: it boots the package, loads migrations, and enables helper availability.
    - `helper-functions/sequence-helpers.php` provides the global entry helper used by consumers.
    - The package is designed as a thin Laravel-facing facade over the internal sequence engine.

11. **Support and domain classes**
    - `Support/NextSequence`, `Support/SequenceConfig`, and `Support/SequenceColumnCollection` form the main fluent API and configuration model.
    - `Models/Sequence` represents the persisted counter record.
    - `Enums/OverflowStrategy` captures the overflow policy in a typed form rather than as loose flags.

12. **Testing and regression strategy**
    - The unit tests focus on the builder, config validation, exceptions, and event construction.
    - The `scripts/` directory adds regression checks, including a concurrency script that simulates parallel workers to verify that locking prevents duplicates.
    - That test layout mirrors the architecture: most logic is pure/configurable, while correctness under load is verified with process-level concurrency tests.

Main entry points: [`src/Support/SequenceConfig.php`](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/SequenceConfig.php) (SequenceConfig), [`src/Support/NextSequence.php`](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/NextSequence.php) (NextSequence), [`src/Exceptions/SequenceException.php`](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceException.php) (SequenceException), [`src/Traits/HasSequence.php`](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Traits/HasSequence.php) (HasSequence trait)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_integration["Laravel integration"]
  node_service_provider["Service Provider<br/>Laravel bootstrap"]
  node_helper["sequence() helper<br/>global helper"]
end

subgraph group_core["Sequence engine"]
  node_next_sequence["NextSequence<br/>fluent builder<br/>[NextSequence.php]"]
  node_sequence_config["SequenceConfig<br/>policy object<br/>[SequenceConfig.php]"]
  node_column_collection["Column map<br/>config collection"]
  node_sequence_flow{{"Reserve flow<br/>runtime flow"}}
end

subgraph group_persistence["Persistence layer"]
  node_sequence_model[("Sequence model<br/>Eloquent model<br/>[Sequence.php]")]
  node_migration["Create sequences<br/>migration"]
end

subgraph group_domain["Domain support"]
  node_overflow_strategy(("OverflowStrategy<br/>enum"))
  node_sequence_assigned(("SequenceAssigned<br/>domain event"))
  node_sequence_exception{{"SequenceException<br/>base exception"}}
  node_config_exception{{"Config errors<br/>exception"}}
  node_transaction_exception{{"Txn errors<br/>exception"}}
  node_validation_exception{{"Validation errors<br/>exception"}}
  node_overflow_exception{{"Overflow errors<br/>exception"}}
end

subgraph group_automation["Model automation"]
  node_has_sequence["HasSequence trait<br/>Eloquent trait<br/>[HasSequence.php]"]
end

subgraph group_verification["Verification"]
  node_regression_scripts["Regression scripts<br/>concurrency checks"]
  node_unit_tests["Unit tests<br/>test suite"]
end

node_service_provider -->|"loads"| node_helper
node_service_provider -->|"publishes"| node_migration
node_helper -->|"creates"| node_next_sequence
node_next_sequence -->|"uses"| node_sequence_config
node_has_sequence -->|"maps"| node_column_collection
node_column_collection -->|"contains"| node_sequence_config
node_has_sequence -->|"delegates"| node_next_sequence
node_next_sequence -->|"drives"| node_sequence_flow
node_sequence_flow -->|"locks"| node_sequence_model
node_sequence_flow -->|"emits"| node_sequence_assigned
node_sequence_flow -->|"requires"| node_transaction_exception
node_sequence_flow -->|"applies"| node_overflow_strategy
node_sequence_model -->|"persists in"| node_migration
node_sequence_config -->|"configures"| node_overflow_strategy
node_sequence_config -->|"validates"| node_config_exception
node_sequence_config -->|"validates"| node_validation_exception
node_sequence_exception -->|"specializes"| node_config_exception
node_sequence_exception -->|"specializes"| node_transaction_exception
node_sequence_exception -->|"specializes"| node_validation_exception
node_sequence_exception -->|"specializes"| node_overflow_exception
node_has_sequence -->|"depends on"| node_transaction_exception
node_unit_tests -->|"covers"| node_next_sequence
node_unit_tests -->|"covers"| node_sequence_config
node_unit_tests -->|"covers"| node_sequence_assigned
node_regression_scripts -->|"verifies"| node_sequence_flow

click node_service_provider "https://github.com/rajeshmk/laravel-sequence/blob/main/src/SequenceServiceProvider.php"
click node_helper "https://github.com/rajeshmk/laravel-sequence/blob/main/helper-functions/sequence-helpers.php"
click node_next_sequence "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/NextSequence.php"
click node_sequence_config "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/SequenceConfig.php"
click node_column_collection "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/SequenceColumnCollection.php"
click node_has_sequence "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Traits/HasSequence.php"
click node_sequence_model "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Models/Sequence.php"
click node_migration "https://github.com/rajeshmk/laravel-sequence/blob/main/database/migrations/2023_01_01_100000_create_sequences.php"
click node_overflow_strategy "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Enums/OverflowStrategy.php"
click node_sequence_assigned "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Events/SequenceAssigned.php"
click node_sequence_exception "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceException.php"
click node_config_exception "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceConfigException.php"
click node_transaction_exception "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceTransactionException.php"
click node_validation_exception "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceValidationException.php"
click node_overflow_exception "https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceOverflowException.php"
click node_regression_scripts "https://github.com/rajeshmk/laravel-sequence/blob/main/scripts/regression_concurrency.php"
click node_unit_tests "https://github.com/rajeshmk/laravel-sequence/blob/main/tests/Unit/NextSequenceTest.php"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_service_provider,node_helper toneBlue
class node_next_sequence,node_sequence_config,node_column_collection,node_sequence_flow toneAmber
class node_sequence_model,node_migration toneMint
class node_overflow_strategy,node_sequence_assigned,node_sequence_exception,node_config_exception,node_transaction_exception,node_validation_exception,node_overflow_exception toneRose
class node_has_sequence toneIndigo
class node_regression_scripts,node_unit_tests toneTeal
```

## Components

### Laravel integration

Framework entry points and consumer-facing helpers.

- [Service Provider](https://github.com/rajeshmk/laravel-sequence/blob/main/src/SequenceServiceProvider.php): Laravel bootstrap · Registers package services, migrations, and helper availability. · `src/SequenceServiceProvider.php`
- [sequence() helper](https://github.com/rajeshmk/laravel-sequence/blob/main/helper-functions/sequence-helpers.php): global helper · Entry helper that creates the fluent sequence builder. · `helper-functions/sequence-helpers.php`

### Sequence engine

Builder, config, and policy that drive sequence reservation.

- [NextSequence](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/NextSequence.php): fluent builder · Collects prefix, padding, grouping, range, and format options before reserving a number. · `src/Support/NextSequence.php`
- [SequenceConfig](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/SequenceConfig.php): policy object · Holds configuration and validation rules for sequence generation. · `src/Support/SequenceConfig.php`
- [Column map](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Support/SequenceColumnCollection.php): config collection · Maps model columns to per-column sequence configuration. · `src/Support/SequenceColumnCollection.php`
- **Reserve flow**: runtime flow · Caller-owned transaction plus locked row increment and formatting.

### Persistence layer

Database-backed counter storage and schema.

- [Sequence model](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Models/Sequence.php): Eloquent model · Persists the counter row keyed by name and group. · `src/Models/Sequence.php`
- [Create sequences](https://github.com/rajeshmk/laravel-sequence/blob/main/database/migrations/2023_01_01_100000_create_sequences.php): migration · Creates the sequences table used for counter storage. · `database/migrations/2023_01_01_100000_create_sequences.php`

### Domain support

Typed values, events, and exceptions.

- [OverflowStrategy](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Enums/OverflowStrategy.php): enum · Typed overflow policy for bounded and cycling ranges. · `src/Enums/OverflowStrategy.php`
- [SequenceAssigned](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Events/SequenceAssigned.php): domain event · Emitted when a sequence value is reserved. · `src/Events/SequenceAssigned.php`
- [SequenceException](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceException.php): base exception · Shared exception root for package failures. · `src/Exceptions/SequenceException.php`
- [Config errors](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceConfigException.php): exception · Invalid configuration and model setup failures. · `src/Exceptions/SequenceConfigException.php`
- [Txn errors](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceTransactionException.php): exception · Raised when sequence generation is attempted without the required transaction. · `src/Exceptions/SequenceTransactionException.php`
- [Validation errors](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceValidationException.php): exception · Raised for invalid values and policy violations. · `src/Exceptions/SequenceValidationException.php`
- [Overflow errors](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Exceptions/SequenceOverflowException.php): exception · Raised when numeric bounds are exceeded without cycling. · `src/Exceptions/SequenceOverflowException.php`

### Model automation

Eloquent trait path for auto-assigning sequences.

- [HasSequence trait](https://github.com/rajeshmk/laravel-sequence/blob/main/src/Traits/HasSequence.php): Eloquent trait · Auto-assigns sequence values during model creation. · `src/Traits/HasSequence.php`

### Verification

Unit and regression coverage for correctness and concurrency.

- [Regression scripts](https://github.com/rajeshmk/laravel-sequence/blob/main/scripts/regression_concurrency.php): concurrency checks · Process-level scripts that exercise locking and first-number behavior. · `scripts/regression_concurrency.php`
- [Unit tests](https://github.com/rajeshmk/laravel-sequence/blob/main/tests/Unit/NextSequenceTest.php): test suite · Covers builder behavior, config validation, exceptions, and event construction. · `tests/Unit/NextSequenceTest.php`

## Connections

- Service Provider → sequence() helper: loads · Exposes the helper and boots package wiring.
- Service Provider → Create sequences: publishes · Registers the migration for the sequences table.
- sequence() helper → NextSequence: creates · Returns a fluent builder for a named sequence.
- NextSequence → SequenceConfig: uses · Applies policy, validation, and formatting options.
- HasSequence trait → Column map: maps · Collects per-column sequence definitions from the model.
- Column map → SequenceConfig: contains · Stores configuration objects for each sequence column.
- HasSequence trait → NextSequence: delegates · Uses the fluent builder to reserve values during model creation.
- NextSequence → Reserve flow: drives · The builder triggers the reservation and formatting path.
- Reserve flow → Sequence model: locks · Reads and increments the matching counter row with row-level locking.
- Reserve flow → SequenceAssigned: emits · Publishes the assigned value after reservation.
- Reserve flow → Txn errors: requires · Depends on an active database transaction for correctness.
- Reserve flow → OverflowStrategy: applies · Uses typed overflow policy to decide failure or cycling behavior.
- Sequence model → Create sequences: persists in · The model is backed by the package-created sequences table.
- SequenceConfig → OverflowStrategy: configures · Encodes bounded and cycling range behavior.
- SequenceConfig → Config errors: validates · Rejects invalid package and sequence configuration.
- SequenceConfig → Validation errors: validates · Enforces input and formatting constraints.
- SequenceException → Config errors: specializes · Configuration failures derive from the shared exception root.
- SequenceException → Txn errors: specializes · Transaction failures derive from the shared exception root.
- SequenceException → Validation errors: specializes · Validation failures derive from the shared exception root.
- SequenceException → Overflow errors: specializes · Overflow failures derive from the shared exception root.
- HasSequence trait → Txn errors: depends on · Still requires the caller to wrap model creation in a transaction.
- Unit tests → NextSequence: covers · Exercises fluent sequence construction and formatting behavior.
- Unit tests → SequenceConfig: covers · Verifies configuration and validation rules.
- Unit tests → SequenceAssigned: covers · Checks event payload construction.
- Regression scripts → Reserve flow: verifies · Confirms locking and concurrency-safe numbering under load.
