1. Go to this page and download the library: Download hatchyu/laravel-sequence library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hatchyu / laravel-sequence example snippets
use Illuminate\Support\Facades\DB;
$value = DB::transaction(function () {
return sequence('sequence_number')->next();
});
// returns "1", then "2", etc.
// When generating directly with multiple group keys
DB::transaction(function () use ($branchId, $year) {
return sequence('customer_code')
->groupBy($branchId, $year)
->next();
});
// When used via HasSequence, configure grouping in SequenceConfig (example below)
use Illuminate\Database\Eloquent\Model;
use Hatchyu\Sequence\Traits\HasSequence;
use Hatchyu\Sequence\Support\SequenceConfig;
use Hatchyu\Sequence\Support\SequenceColumnCollection;
class CustomerProfile extends Model
{
use HasSequence;
protected function sequenceColumns(): SequenceColumnCollection
{
return SequenceColumnCollection::collection()
->column(
'customer_code',
SequenceConfig::create()
->prefix('CU')
->padLength(3)
// optional: make sequence per-branch (or per branch+year, etc.)
->groupBy($this->branch_id)
);
}
}
use Hatchyu\Sequence\Events\SequenceAssigned;
use Illuminate\Support\Facades\Event;
Event::listen(SequenceAssigned::class, function (SequenceAssigned $event) {
// $event->name, $event->rawNumber, $event->sequenceNumber, $event->groupByKey
});
use Illuminate\Foundation\Testing\RefreshDatabase;
use Hatchyu\Sequence\Events\SequenceAssigned;
uses(RefreshDatabase::class);
it('generates sequential sequence numbers', function () {
$value1 = DB::transaction(fn() => sequence('test')->next());
$value2 = DB::transaction(fn() => sequence('test')->next());
expect($value1)->toBe('1');
expect($value2)->toBe('2');
});
it('dispatches sequence number assigned event', function () {
Event::fake();
DB::transaction(fn() => sequence('test')->next());
Event::assertDispatched(SequenceAssigned::class);
});
use Hatchyu\Sequence\Exceptions\SequenceException;
use Hatchyu\Sequence\Exceptions\SequenceOverflowException;
use Hatchyu\Sequence\Exceptions\SequenceTransactionException;
try {
DB::transaction(fn () => sequence('orders')->next());
} catch (SequenceOverflowException $e) {
// max reached and overflow strategy is FAIL
throw $e;
} catch (SequenceTransactionException $e) {
if ($e->getCode() === SequenceTransactionException::CODE_TRANSACTION_NOT_INITIATED) {
// handle missing transaction specifically
}
throw $e;
} catch (SequenceException $e) {
// handle any other sequence error
throw $e;
}