dive-be / laravel-snowflake
Generate identifiers using Twitter Snowflake
Requires
- php: ~8.3
- godruoyi/php-snowflake: ^3.0
- illuminate/cache: ^11.0
- illuminate/contracts: ^11.0
- illuminate/database: ^11.0
- illuminate/support: ^11.0
Requires (Dev)
- larastan/larastan: ^2.0
- laravel/pint: ^1.0
- orchestra/testbench: ^9.0
- phpunit/phpunit: ^11.0
This package is auto-updated.
Last update: 2024-10-22 12:06:54 UTC
README
❄️ Generate IDs using Twitter Snowflake
This package assists you in creating Snowflake identifiers for your Eloquent models.
It is a Laravel wrapper for godruoyi/php-snowflake.
What problem does this package solve?
Please refer to the original library for more information regarding Snowflakes.
Installation
You can install the package via composer:
composer require dive-be/laravel-snowflake
You can publish the config file with:
php artisan vendor:publish --provider="Dive\Snowflake\ServiceProvider" --tag="config"
This is the contents of the published config file:
return [ /** * Set this value to today when starting a new app. * You will have 69 years before you run out of snowflakes. */ 'start_date' => '2022-04-10', ];
Usage
⚠️ Use a high-performing cache driver such as
Redis
to ensure rapid ID generation.
❗️ Do not use an ephemeral cache driver such as
array
in production!
Migrations
- Use
snowflake
to define a Snowflake column - Use
foreignSnowflake
to reference another Snowflake (alias forforeignId
)
Schema::table('products', static function (Blueprint $table) { $table->snowflake(); $table->foreignSnowflake('variant_id')->constrained(); });
Models
Use the HasSnowflake
trait in your Eloquent models:
class Product extends Model { use HasSnowflake; }
Manual generation
You have a couple of options if you'd like to generate your Snowflake identifiers manually:
Snowflake::id(); // Facade snowflake(); // Helper app('snowflake'); // Service Locator // Dependency Injection public function __construct(\Godruoyi\Snowflake\Snowflake $snowflake) {}
📣 Note on JavaScript compatibility
While JavaScript itself actually supports BigInt
s,
the JSON
standard does not.
JSON.parse("{\"a\":10n}") // Uncaught SyntaxError: Unexpected token n in JSON at position 7
Therefore, to make sure the identifiers are not truncated while deserializing them on the front-end using JSON.parse
and alike,
the package will automatically cast the models' id
field to string
.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email oss@dive.be instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.