dive-be/laravel-snowflake

Generate identifiers using Twitter Snowflake

1.3.0 2024-03-14 12:59 UTC

This package is auto-updated.

Last update: 2024-04-22 11:12:03 UTC


README

Social Card of Laravel Dry Requests

❄️ Generate IDs using Twitter Snowflake

Latest Version on Packagist

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 for foreignId)
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 BigInts, 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.