### Install Laravel Snowflake Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Install the package using Composer and publish its configuration file. ```bash composer require "kra8/laravel-snowflake" php artisan vendor:publish --provider="Kra8\Snowflake\Providers\LaravelServiceProvider" ``` -------------------------------- ### Install Lumen Snowflake Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Install the package via Composer and register the service provider in bootstrap/app.php. ```bash composer require "kra8/laravel-snowflake" ``` ```php // Add this line $app->register(Kra8\Snowflake\Providers\LumenServiceProvider::class); ``` -------------------------------- ### Install Laravel Snowflake Package Source: https://context7.com/kra8/laravel-snowflake/llms.txt Install the package via Composer and publish the configuration file for Laravel. For Lumen, register the service provider manually in bootstrap/app.php. ```bash # Laravel composer require "kra8/laravel-snowflake" php artisan vendor:publish --provider="Kra8\Snowflake\Providers\LaravelServiceProvider" ``` ```php // Lumen — add to bootstrap/app.php manually // $app->register(Kra8\Snowflake\Providers\LumenServiceProvider::class); ``` -------------------------------- ### Get Snowflake Instance Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Retrieve an instance of the Snowflake generator using the application container. ```php $snowflake = $this->app->make('Kra8\Snowflake\Snowflake'); ``` ```php $snowflake = app('Kra8\Snowflake\Snowflake'); ``` -------------------------------- ### Eloquent Migration with Auto-Increment ID Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Example of a migration creating a 'users' table with an auto-incrementing 'id' column. The HasSnowflakePrimary trait will override this behavior for the primary key. ```php /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } ``` -------------------------------- ### Snowflake::makeSequenceId() Source: https://context7.com/kra8/laravel-snowflake/llms.txt Manages the internal 12-bit sequence counter. This method returns an incrementing sequence number for calls within the same millisecond and resets to a random value at the start of a new millisecond. It is publicly exposed for testing and advanced custom usage. ```APIDOC ## `Snowflake::makeSequenceId()` — Sequence Number Management Internal method that manages the 12-bit sequence counter. Returns an incrementing sequence number when called multiple times within the same millisecond, and resets to a random value between 0 and `$max` at the start of a new millisecond. Exposed as `public` for testing and advanced custom usage. ```php timestamp(); // current Unix time in ms // Same millisecond — sequence increments $seq1 = $snowflake->makeSequenceId($currentTime); // e.g. 42 (random seed) $seq2 = $snowflake->makeSequenceId($currentTime); // 43 $seq3 = $snowflake->makeSequenceId($currentTime); // 44 // Different millisecond — sequence resets to a new random value $laterTime = $currentTime + 1; $seq4 = $snowflake->makeSequenceId($laterTime); // e.g. 17 (new random seed) echo $seq1; // 42 echo $seq2; // 43 echo $seq4; // 17 ``` ``` -------------------------------- ### Publish Configuration Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Publish the configuration file if it does not exist by running the vendor:publish Artisan command. ```bash php artisan vendor:publish ``` -------------------------------- ### Configure Snowflake Settings Source: https://context7.com/kra8/laravel-snowflake/llms.txt Configure the epoch, worker ID, and datacenter ID in the published config/snowflake.php file or via .env variables. The epoch should be set to your application's deployment date. ```php // config/snowflake.php return [ // Set to the date your application was first deployed. Never change after IDs are issued. 'epoch' => env('SNOWFLAKE_EPOCH', '2019-04-01 00:00:00'), // Unique ID (1–31) for each server in a multi-server setup 'worker_id' => env('SNOWFLAKE_WORKER_ID', 1), 'datacenter_id' => env('SNOWFLAKE_DATACENTER_ID', 1), ]; ``` ```ini # .env SNOWFLAKE_EPOCH=2024-01-01 00:00:00 SNOWFLAKE_WORKER_ID=2 SNOWFLAKE_DATACENTER_ID=3 ``` -------------------------------- ### Generate 64-bit Snowflake ID Source: https://context7.com/kra8/laravel-snowflake/llms.txt Generate a unique 63-bit integer ID using the `next()` or `id()` method. This ID includes timestamp, datacenter, worker, and sequence information. The sequence number increments per millisecond, and the generator will block if the sequence overflows. ```php next(); // e.g. 7304672964460544 $id = $snowflake->id(); // identical alias echo $id; // 7304672964460544 echo gettype($id); // integer // Generate multiple IDs — all are guaranteed unique $ids = []; for ($i = 0; $i < 1000; $i++) { $ids[] = $snowflake->next(); } assert(array_unique($ids) === $ids); // true — all unique ``` ```php // Standalone usage without Laravel (custom epoch, workerId, datacenterId) use Kra8\Snowflake\Snowflake; $snowflake = new Snowflake( strtotime('2024-01-01 00:00:00'), // epoch as Unix timestamp workerId: 2, datacenterId: 3 ); $id = $snowflake->next(); echo $id; // e.g. 190842631987200 ``` -------------------------------- ### Manage Sequence Numbers with `Snowflake::makeSequenceId()` Source: https://context7.com/kra8/laravel-snowflake/llms.txt This internal method manages the 12-bit sequence counter, providing incrementing numbers within the same millisecond and resetting to a new random value for new milliseconds. It's exposed for testing and advanced customization. ```php timestamp(); // current Unix time in ms // Same millisecond — sequence increments $seq1 = $snowflake->makeSequenceId($currentTime); // e.g. 42 (random seed) $seq2 = $snowflake->makeSequenceId($currentTime); // 43 $seq3 = $snowflake->makeSequenceId($currentTime); // 44 // Different millisecond — sequence resets to a new random value $laterTime = $currentTime + 1; $seq4 = $snowflake->makeSequenceId($laterTime); // e.g. 17 (new random seed) echo $seq1; // 42 echo $seq2; // 43 echo $seq4; // 17 ``` -------------------------------- ### Generate Snowflake Identifier Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Generate a unique 64-bit Snowflake identifier using the next() method. ```php $id = $snowflake->next(); ``` -------------------------------- ### Generate 53-bit JavaScript-Safe ID Source: https://context7.com/kra8/laravel-snowflake/llms.txt Generate a 53-bit integer ID using the `short()` method, suitable for JavaScript clients. This ID omits worker and datacenter bits, ensuring it remains within `Number.MAX_SAFE_INTEGER` when serialized to JSON. ```php short(); // e.g. 219318497280 echo $shortId; // 219318497280 echo gettype($shortId); // integer // Verify it's within JS safe integer range assert($shortId <= 9007199254740991); // Number.MAX_SAFE_INTEGER // Generate many short IDs — all unique $ids = []; for ($i = 0; $i < 1000; $i++) { $ids[] = $snowflake->short(); } assert(array_unique($ids) === $ids); // true ``` -------------------------------- ### Snowflake::next() / Snowflake::id() - Generate a 64-bit Snowflake ID Source: https://context7.com/kra8/laravel-snowflake/llms.txt Generates a unique 63-bit integer ID composed of a timestamp, datacenter ID, worker ID, and sequence number. Both `next()` and `id()` are aliases for this operation. The sequence number increments for IDs generated within the same millisecond. ```APIDOC ## Snowflake::next() / Snowflake::id() ### Description Generates a unique 63-bit integer ID composed of a 41-bit millisecond timestamp offset from the configured epoch, 5-bit datacenter ID, 5-bit worker ID, and 12-bit sequence number. The sequence number automatically increments for IDs generated within the same millisecond, and the generator blocks if the sequence overflows 4095 within a single millisecond. ### Method `next()` or `id()` ### Parameters None ### Request Example ```php // Resolve from the service container $snowflake = app('Kra8\Snowflake\Snowflake'); // or $snowflake = app(\Kra8\Snowflake\Snowflake::class); $id = $snowflake->next(); // e.g. 7304672964460544 $id = $snowflake->id(); // identical alias echo $id; ``` ### Response #### Success Response - **id** (integer) - A unique 63-bit Snowflake ID. ### Response Example ```json { "id": 7304672964460544 } ``` ### Standalone Usage Example ```php use Kra8\Snowflake\Snowflake; $snowflake = new Snowflake( strtotime('2024-01-01 00:00:00'), // epoch as Unix timestamp workerId: 2, datacenterId: 3 ); $id = $snowflake->next(); echo $id; // e.g. 190842631987200 ``` ``` -------------------------------- ### Auto-assign JavaScript-Safe IDs with `HasShortflakePrimary` Source: https://context7.com/kra8/laravel-snowflake/llms.txt This trait functions like `HasSnowflakePrimary` but uses `Snowflake::short()` to generate 53-bit IDs, suitable for JavaScript environments to prevent precision loss. The database schema should still accommodate these IDs, typically with BIGINT. ```php id(); $table->string('title'); $table->timestamps(); }); // Usage $post = Post::create(['title' => 'Hello World']); echo $post->id; // e.g. 219318497280 (fits within JS Number.MAX_SAFE_INTEGER) // Safe to serialize to JSON and use in JavaScript $json = json_encode(['id' => $post->id, 'title' => $post->title]); // {"id":219318497280,"title":"Hello World"} // No precision loss in JS: Number(219318497280) === 219318497280 ✓ ``` -------------------------------- ### Auto-assign Snowflake Primary Keys with `HasSnowflakePrimary` Source: https://context7.com/kra8/laravel-snowflake/llms.txt Use this trait in your Eloquent models to automatically assign a 64-bit Snowflake ID as the primary key upon saving. Ensure your database schema uses a compatible column type like BIGINT UNSIGNED. ```php id(); // BIGINT UNSIGNED — holds 64-bit Snowflake IDs $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); // Usage — ID is assigned automatically on save $user = new User(['name' => 'Alice', 'email' => 'alice@example.com', 'password' => bcrypt('secret')]); $user->save(); echo $user->id; // e.g. 7304672964460544 (auto-generated Snowflake ID) echo gettype($user->id); // integer // Retrieval by Snowflake ID works normally $found = User::find(7304672964460544); echo $found->name; // Alice ``` -------------------------------- ### Eloquent Model with JavaScript-Compatible ID Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Use the HasShortflakePrimary trait for models where the primary key needs to be a 53-bit integer compatible with JavaScript. This also sets `$incrementing` to false. ```php id(); $table->string('title'); $table->timestamps(); }); // Usage $post = Post::create(['title' => 'Hello World']); echo $post->id; // e.g. 219318497280 (fits within JS Number.MAX_SAFE_INTEGER) // Safe to serialize to JSON and use in JavaScript $json = json_encode(['id' => $post->id, 'title' => $post->title]); // {"id":219318497280,"title":"Hello World"} // No precision loss in JS: Number(219318497280) === 219318497280 ✓ ``` ``` -------------------------------- ### Snowflake::short() - Generate a 53-bit JavaScript-Safe ID Source: https://context7.com/kra8/laravel-snowflake/llms.txt Generates a 53-bit integer ID that fits safely within JavaScript's `Number.MAX_SAFE_INTEGER`. This is useful when IDs need to be serialized to JSON and consumed by JavaScript clients. ```APIDOC ## Snowflake::short() ### Description Generates a 53-bit integer ID (timestamp bits + sequence bits only, omitting worker/datacenter bits) that fits safely within JavaScript's `Number.MAX_SAFE_INTEGER` (2^53 - 1). Use this variant when IDs will be serialized to JSON and consumed by JavaScript clients where 64-bit integers would lose precision. ### Method `short()` ### Parameters None ### Request Example ```php $snowflake = app(\'Kra8\Snowflake\Snowflake::class); $shortId = $snowflake->short(); // e.g. 219318497280 echo $shortId; ``` ### Response #### Success Response - **shortId** (integer) - A unique 53-bit JavaScript-safe ID. ### Response Example ```json { "shortId": 219318497280 } ``` ### Verification Example ```php // Verify it's within JS safe integer range assert($shortId <= 9007199254740991); // Number.MAX_SAFE_INTEGER ``` ``` -------------------------------- ### Snowflake::parse() Source: https://context7.com/kra8/laravel-snowflake/llms.txt Decodes a 64-bit Snowflake ID integer into its components: timestamp, sequence number, worker ID, datacenter ID, and the original generation datetime. This is useful for debugging, auditing, and verifying ID integrity. ```APIDOC ## `Snowflake::parse()` — Decode a Snowflake ID into Its Components Accepts a previously generated 64-bit Snowflake ID integer and decodes it back into its binary representation and constituent fields: timestamp, sequence number, worker ID, datacenter ID, and the original generation datetime. Useful for debugging, auditing, and verifying ID integrity. ```php next(); $parts = $snowflake->parse($id); /* Example output: [ 'binary_length' => 63, 'binary' => '111000011001001100000000000000000000000000100000000000000001', 'binary_timestamp' => '11100001100100110000000000000000000000000', 'binary_sequence' => '000000000001', 'binary_worker_id' => '00001', 'binary_datacenter_id' => '00001', 'timestamp' => 1900800000, // ms offset from epoch 'sequence' => 1, 'worker_id' => 1, 'datacenter_id' => 1, 'epoch' => 1609459200000, // configured epoch in ms 'datetime' => '2024-11-15 08:53:20', ] */ echo $parts['datetime']; // '2024-11-15 08:53:20' echo $parts['worker_id']; // 1 echo $parts['datacenter_id']; // 1 echo $parts['sequence']; // 1 echo $parts['timestamp']; // millisecond offset from epoch ``` ``` -------------------------------- ### Decode Snowflake ID with `Snowflake::parse()` Source: https://context7.com/kra8/laravel-snowflake/llms.txt Use this method to decode a generated Snowflake ID into its constituent parts, including binary representation, timestamp, sequence number, and worker/datacenter IDs. This is useful for debugging and auditing. ```php next(); $parts = $snowflake->parse($id); /* Example output: [ 'binary_length' => 63, 'binary' => '111000011001001100000000000000000000000000100000000000000001', 'binary_timestamp' => '11100001100100110000000000000000000000000', 'binary_sequence' => '000000000001', 'binary_worker_id' => '00001', 'binary_datacenter_id' => '00001', 'timestamp' => 1900800000, // ms offset from epoch 'sequence' => 1, 'worker_id' => 1, 'datacenter_id' => 1, 'epoch' => 1609459200000, // configured epoch in ms 'datetime' => '2024-11-15 08:53:20', ] */ echo $parts['datetime']; // '2024-11-15 08:53:20' echo $parts['worker_id']; // 1 echo $parts['datacenter_id']; // 1 echo $parts['sequence']; // 1 echo $parts['timestamp']; // millisecond offset from epoch ``` -------------------------------- ### HasSnowflakePrimary Trait Source: https://context7.com/kra8/laravel-snowflake/llms.txt Automatically assigns a 64-bit Snowflake ID as the primary key for Eloquent models upon saving. It ensures IDs are unique and compatible with database schema definitions like BIGINT UNSIGNED. ```APIDOC ## `HasSnowflakePrimary` Trait — Auto-assign 64-bit Snowflake Primary Keys in Eloquent A model trait that hooks into Eloquent's `saving` event to automatically generate and assign a 64-bit Snowflake ID as the primary key before the model is first saved. Automatically sets `$incrementing` to `false` so Laravel does not try to retrieve a last-insert-id from the database. Compatible with `$table->id()` (BIGINT UNSIGNED) or `$table->unsignedBigInteger('id')` column types. ```php id(); // BIGINT UNSIGNED — holds 64-bit Snowflake IDs $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); // Usage — ID is assigned automatically on save $user = new User(['name' => 'Alice', 'email' => 'alice@example.com', 'password' => bcrypt('secret')]); $user->save(); echo $user->id; // e.g. 7304672964460544 (auto-generated Snowflake ID) echo gettype($user->id); // integer // Retrieval by Snowflake ID works normally $found = User::find(7304672964460544); echo $found->name; // Alice ``` ``` -------------------------------- ### Eloquent Model with Snowflake Primary Key Source: https://github.com/kra8/laravel-snowflake/blob/main/README.md Use the HasSnowflakePrimary trait in your Eloquent model to set a Snowflake ID as the primary key. This automatically sets `$incrementing` to false. ```php