PHPackages                             calebdw/laraflake - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. calebdw/laraflake

ActiveLibrary[Database &amp; ORM](/categories/database)

calebdw/laraflake
=================

A Laravel package to create X/Twitter Snowflake identifiers.

v2.3.0(2mo ago)625.4k—7.1%3MITPHPPHP ^8.4CI failing

Since Jul 19Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/calebdw/laraflake)[ Packagist](https://packagist.org/packages/calebdw/laraflake)[ Docs](https://github.com/calebdw/laraflake)[ GitHub Sponsors](https://github.com/calebdw)[ RSS](/packages/calebdw-laraflake/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (18)Versions (12)Used By (0)

 [![Laraflake](/art/laraflake.webp)](/art/laraflake.webp)

Generate X/Twitter [Snowflake identifiers](https://en.wikipedia.org/wiki/Snowflake_ID) in Laravel.

 [![Test Results](https://github.com/calebdw/laraflake/actions/workflows/tests.yml/badge.svg)](https://github.com/calebdw/laraflake/actions/workflows/tests.yml) [![Code Coverage](https://camo.githubusercontent.com/e78b8fc08705753d5866176288917db652274c7d400b8e674eb0ba5ab5d35a25/68747470733a2f2f636f6465636f762e696f2f6769746875622f63616c656264772f6c617261666c616b652f67726170682f62616467652e7376673f746f6b656e3d52504c514b57444d3547)](https://codecov.io/github/calebdw/laraflake) [![License](https://camo.githubusercontent.com/7026a4ec9d5ac8ae96c7fe17e3e3c494b159a97f9d3b5dc13a1c1ef710e87fd0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f63616c656264772f6c617261666c616b65)](https://github.com/calebdw/laraflake) [![Packagist Version](https://camo.githubusercontent.com/2772fb4c217200b278ef8cf680bfc2ab3e49142de58442bbb4a70ef1f2268650/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63616c656264772f6c617261666c616b652e737667)](https://packagist.org/packages/calebdw/laraflake) [![Total Downloads](https://camo.githubusercontent.com/2cb268c8dffe1e4a8d13c2befd51d2cbc43096107ef38abe878dc61b9c91ae8f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f63616c656264772f6c617261666c616b652e737667)](https://packagist.org/packages/calebdw/laraflake)

What are Snowflakes?
--------------------

[](#what-are-snowflakes)

Snowflakes are a form of unique identifier [devised by X/Twitter](https://blog.x.com/engineering/en_us/a/2010/announcing-snowflake) and are used by many companies, including Instagram and Discord, to generate unique IDs for their entities.

Some of the benefits of using Snowflakes (over alternatives such as UUID/ULID) include:

- **Timestamp Component:** Extract creation time directly from the ID.
- **Uniqueness Across Distributed Systems:** Ensures unique IDs without coordination.
- **Orderability:** Roughly ordered by creation time for easy sorting.
- **Compactness:** 64-bit size, more compact than 128-bit UUIDs.
- **Performance:** Faster and less resource-intensive generation.
- **Configurability:** Flexible bit allocation for specific needs.
- **Storage Efficiency:** More efficient storage compared to larger identifiers.
- **Database Indexing:** Faster indexing and query performance.
- **Human Readability:** More compact and readable than longer identifiers.

Installation
------------

[](#installation)

First pull in the package using Composer:

```
composer require calebdw/laraflake
```

And then publish the package's configuration file:

```
php artisan vendor:publish --provider="CalebDW\Laraflake\ServiceProvider"
```

Configuration
-------------

[](#configuration)

### Snowflake Type

[](#snowflake-type)

The Snowflake type determines the class used to generate Snowflakes.

The default Snowflake type is `Godruoyi\Snowflake\Snowflake` which uses 41 bits for the epoch, 5 bits for the data center ID, 5 bits for the worker ID, and 12 bits for the sequence. This allows for up to `1024` workers and `4096` unique IDs per worker per millisecond.

You can change the Snowflake type to `Godruoyi\Snowflake\Sonyflake` which uses 39 bits for the epoch, 16 bits for the machine ID, and 8 bits for the sequence. This allows for up to `65535` machines and `256` unique IDs per worker per *10 milliseconds*.

### Epoch

[](#epoch)

The timestamp encoded in the Snowflake is the difference between the time of creation and a given starting epoch/timestamp. Snowflakes use 41 bits and can generate IDs for up to 69 years past the given epoch. Sonyflakes use 39 bits and can generate IDs for up to 174 years past the given epoch.

In most cases you should set this value to the current date using a format of `YYYY-MM-DD`.

> **Note**: Future dates will throw an error and you should avoid using a date far in the past (such as the Unix epoch `1970-01-01`) as that may reduce the number of years for which you can generate timestamps.

### Data Center &amp; Worker IDs

[](#data-center--worker-ids)

> **Note**: This is only used for the `Snowflake` type.

You can set the data center and worker IDs that the application should use when generating Snowflakes. These are used to ensure that each worker generates unique Snowflakes and can range from `0` to `31` (up to `1024` unique workers).

### Machine ID

[](#machine-id)

> **Note**: This is only used for the `Sonyflake` type.

You can set the machine ID that the application should use when generating Sonyflakes. This is used to ensure that each machine generates unique Sonyflakes and can range from `0` to `65535`.

Usage
-----

[](#usage)

> **WARNING**: Do not create new instances of the Snowflake generator (as this could cause collisions), always use the Snowflake singleton from the container.

You can generate a Snowflake by resolving the singleton from the container and calling its `id` method:

```
use Godruoyi\Snowflake\Snowflake;

resolve('snowflake')->id();      // (string) "5585066784854016"
resolve(Snowflake::class)->id(); // (string) "5585066784854016"
```

This package also provides a `snowflake` helper function, a `Snowflake` facade, and a `Str::snowflakeId` macro for convenience:

```
use CalebDW\Laraflake\Facades\Snowflake;
use Illuminate\Support\Str;

snowflake()->id();  // (string) "5585066784854016"
Snowflake::id();    // (string) "5585066784854016"
Str::snowflakeId(); // (string) "5585066784854016"
```

### Eloquent Integration

[](#eloquent-integration)

#### Migrations

[](#migrations)

This package provides a set of migration macros to make it easier to work with Snowflakes in your database schema.

Here's an example:

```
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('comments', function(Blueprint $table) {
            $table->snowflake()->primary();
            $table->foreignSnowflake('user_id')->constrained()->cascadeOnDelete();
            $table->foreignSnowflakeFor(Post::class)->constrained();
        });
    }
}
```

#### Models

[](#models)

Next, add the package's `HasSnowflakes` trait to your Eloquent models:

```
namespace App\Models;

use CalebDW\Laraflake\Concerns\HasSnowflakes;

class Post extends Model
{
    use HasSnowflakes;
}
```

The trait provides several features for the model's Snowflake columns:

- the generation of Snowflakes for new records
- route model binding
- automatic casting from database integers to strings which prevents truncation in languages that do not support 64-bit integers (such as JavaScript).

By default, the trait assumes that the model's primary key is a Snowflake. If you have other unique columns that should be treated as Snowflakes, you can override the `uniqueIds` method to specify them:

```
namespace App\Models;

use CalebDW\Laraflake\Concerns\HasSnowflakes;

class Post extends Model
{
    use HasSnowflakes;

    /** @inheritDoc */
    public function uniqueIds(): array
    {
        return [$this->getKeyName(), 'slug'];
    }
}
```

If necessary, you can explicitly cast the model's Snowflake columns using the `AsSnowflake` cast:

```
namespace App\Models;

use CalebDW\Laraflake\Casts\AsSnowflake;
use CalebDW\Laraflake\Concerns\HasSnowflakes;

class Post extends Model
{
    use HasSnowflakes;

    protected $casts = [
        'id'      => AsSnowflake::class,
        'user_id' => AsSnowflake::class,
    ];
}
```

### Validation

[](#validation)

If you need to validate Snowflakes in your application, you can use the `Snowflake` rule or the `Rule::snowflake` macro provided by this package:

```
use CalebDW\Laraflake\Rules\Snowflake;
use Illuminate\Validation\Rule;

$request->validate([
    'id'      => ['required', new Snowflake()],
    'user_id' => ['required', Rule::snowflake()],
]);
```

You can also just use the `Str::isSnowflake` macro to check if a value is a valid Snowflake:

```
use Illuminate\Support\Str;

Str::isSnowflake('5585066784854016'); // (bool) true
```

### Sequence Resolver

[](#sequence-resolver)

The sequence resolver is responsible for generating the sequence component of the Snowflake to ensure that numbers generated on the same machine within the same millisecond are unique.

By default, if the application has a cache, then it uses the `LaravelSequenceResolver`which uses the Laravel cache to store the last sequence number. If the application does not have a cache, then it uses the `RandomSequenceResolver` which has no dependencies **but is not concurrency-safe**.

You can override the sequence resolver by binding your own implementation in a service provider:

```
use Godruoyi\Snowflake\SequenceResolver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(SequenceResolver::class, function() {
            return new MySequenceResolver();
        });
    }
}
```

Please see [godruoyi/php-snowflake](https://github.com/godruoyi/php-snowflake) for more information on the available sequence resolvers and their dependencies.

Contributing
------------

[](#contributing)

Thank you for considering contributing! You can read the contribution guide [here](CONTRIBUTING.md).

License
-------

[](#license)

Laraflake is open-sourced software licensed under the [MIT license](LICENSE).

Acknowledgments
---------------

[](#acknowledgments)

Derived from [caneara/snowflake](https://github.com/caneara/snowflake) which is no longer maintained. The actual Snowflake generation is handled by the excellent [godruoyi/php-snowflake](https://github.com/godruoyi/php-snowflake) library.

Alternatives
------------

[](#alternatives)

- [caneara/snowflake](https://github.com/caneara/snowflake)
- [kra8/laravel-snowflake](https://github.com/kra8/laravel-snowflake)
- [dive-be/laravel-snowflake](https://github.com/dive-be/laravel-snowflake)
- [hafael/laraflake](https://github.com/hafael/laraflake)

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance89

Actively maintained with recent releases

Popularity36

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 69.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~76 days

Recently: every ~104 days

Total

9

Last Release

61d ago

Major Versions

v1.1.0 → v2.0.02025-01-26

PHP version history (2 changes)v1.0.0PHP ^8.1

v2.0.0PHP ^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/b188ac4984d22fd742e5a2654677043a28ddd364b867f41c6aeea654b6fe74b6?d=identicon)[calebdw](/maintainers/calebdw)

---

Top Contributors

[![calebdw](https://avatars.githubusercontent.com/u/4176520?v=4)](https://github.com/calebdw "calebdw (37 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (13 commits)")[![ItsReddi](https://avatars.githubusercontent.com/u/3147888?v=4)](https://github.com/ItsReddi "ItsReddi (3 commits)")

---

Tags

distributed-id-generatorlaravelsnowflakesnowflake-idtwittertwitter-snowflaketwitter-snowflake-algorithmunique-idunique-id-generatorphplaraveldatabaseidsidentifiertwitterunique-iddistributedtimestampsnowflakeunique identifier

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/calebdw-laraflake/health.svg)

```
[![Health](https://phpackages.com/badges/calebdw-laraflake/health.svg)](https://phpackages.com/packages/calebdw-laraflake)
```

###  Alternatives

[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[glushkovds/phpclickhouse-laravel

Adapter of the most popular library https://github.com/smi2/phpClickHouse to Laravel

2031.2M2](/packages/glushkovds-phpclickhouse-laravel)[io238/laravel-iso-countries

Ready-to-use Laravel models and relations for country (ISO 3166), language (ISO 639-1), and currency (ISO 4217) information with multi-language support.

5462.3k](/packages/io238-laravel-iso-countries)[cybercog/laravel-clickhouse

ClickHouse migrations for Laravel

163166.8k](/packages/cybercog-laravel-clickhouse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
