PHPackages                             glhd/bits - 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. glhd/bits

ActiveLibrary

glhd/bits
=========

0.6.2(1mo ago)92371.7k—7.3%16[3 PRs](https://github.com/glhd/bits/pulls)2MITPHPPHP ^8.1CI passing

Since Jul 1Pushed 1y ago2 watchersCompare

[ Source](https://github.com/glhd/bits)[ Packagist](https://packagist.org/packages/glhd/bits)[ RSS](/packages/glhd-bits/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (12)Versions (20)Used By (2)

 [ ![Build Status](https://github.com/glhd/bits/workflows/PHPUnit/badge.svg) ](https://github.com/glhd/bits/actions) [ ![Coverage Status](https://camo.githubusercontent.com/80a968af7dbdaf8a1c86d1d3bc80efadd7e5f9c5561f0971b8d4b4946eb861c4/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f36643634383566303161333131386633386136332f746573745f636f766572616765) ](https://codeclimate.com/github/glhd/bits/test_coverage) [ ![Latest Stable Release](https://camo.githubusercontent.com/a7965edac6769adece7d962a6053d028526582a40d473aab5df439b5dc896e08/68747470733a2f2f706f7365722e707567782e6f72672f676c68642f626974732f762f737461626c65) ](https://packagist.org/packages/glhd/bits) [ ![MIT Licensed](https://camo.githubusercontent.com/acd71150cc10c68b34c3943ecd3cb735e8fbaa0f19cb3e9e51c9d7a7f4483e5f/68747470733a2f2f706f7365722e707567782e6f72672f676c68642f626974732f6c6963656e7365) ](./LICENSE) [ ![Follow @inxilpro on Twitter](https://camo.githubusercontent.com/e6d0a3893c652423c3a7c6aa648ca6e98a3b06899551e17a2fe5b33528244dcb/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f666f6c6c6f772f696e78696c70726f3f7374796c653d736f6369616c) ](https://twitter.com/inxilpro) [ ![Follow @chris@any.dev on Mastodon](https://camo.githubusercontent.com/4653377a822fb3e7af6b6b165003eef83ad6676e5f7eed369e75944f319fa014/68747470733a2f2f696d672e736869656c64732e696f2f6d6173746f646f6e2f666f6c6c6f772f3130393538343030313639333733393831333f646f6d61696e3d6874747073253341253246253246616e792e646576267374796c653d736f6369616c) ](https://any.dev/@chris)

Bits
====

[](#bits)

**Bits** is a PHP library for generating unique 64-bit identifiers for use in distributed computing. You can use **Bits** to create [Twitter Snowflake IDs](https://en.wikipedia.org/wiki/Snowflake_ID), [Sonyflake IDs](https://github.com/sony/sonyflake), or any other unique ID that uses bit sequences.

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

[](#installation)

```
composer require glhd/bits
```

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

[](#configuration)

Warning

If you do not configure the worker ID and datacenter ID, you may run into concurrency issues using Bits on multiple app servers.

There are two things you will need to configure to ensure that your IDs are valid and unique.

### Set the `BITS_WORKER_ID` and `BITS_DATACENTER_ID`

[](#set-the-bits_worker_id-and-bits_datacenter_id)

Snowflakes are so compact because they rely on the fact that each worker has its own ID. If you are running multiple servers in multiple datacenters, you need to give each a unique value. You need to set a unique `BITS_DATACENTER_ID` (0-31) for each datacenter your application uses, and each worker in the same datacenter should have a unique `BITS_WORKER_ID` (0-31). This means that you can have, at most, 1024 separate workers generating snowflakes at the same exact moment in time.

Note

If you use Lambda, this can be an issue. Eventually, we hope to have a serverless solution for Bits, but right now you need to manage locking/releasing IDs yourself if you're generating snowflakes in something like Laravel Vapor.

### Set the `BITS_EPOCH`

[](#set-the-bits_epoch)

Another reason snowflakes are compact is because they use a custom "epoch" value (rather than the Unix epoch of January 1, 1970). This is the earliest a snowflake can be generated, and also set the limit to how far in the future snowflakes can be generated. By default, this value is `2023-01-01`, which should be fine for most systems. But if you're going to use time-travel to before January 2023 in your tests, this may cause problems (in which case you should set your epoch to before the earliest moment you would time-travel).

Usage
-----

[](#usage)

To get a new snowflake ID, simply call `Snowflake::make()`. This returns a new `Snowflake object`:

```
class Snowflake
{
    public readonly int $timestamp;
    public readonly int $datacenter_id;
    public readonly int $worker_id;
    public readonly int $sequence;

    public function id(): int;
    public function is(Snowflake $other): bool;
}
```

You can also use the `snowflake()` or `sonyflake()` global helper functions, if you prefer.

All Bits IDs implement `__toString()` and the Laravel `Query\Expression` interface so that you can easily pass them around without juggling types.

### Usage with JavaScript

[](#usage-with-javascript)

It's important to note that JavaScript only supports [~52-bit integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)so if you're passing Snowflakes to JavaScript, be sure to cast them to a string.

All Bits IDs implement `Jsonable` and `JsonSerializable`, so if you pass a Bits instance to `json_encode` it will automatically handle this for you. But if you're using integer IDs that were generated by Bits, you will have to cast them yourself.

### Usage with Eloquent Models

[](#usage-with-eloquent-models)

Bits provides a `HasSnowflakes` trait that behaves the same as [Eloquent’s `HasUuids` and `HasUlids` traits](https://laravel.com/docs/10.x/eloquent#uuid-and-ulid-keys). Simply add `HasSnowflakes` to your model, and whenever they're inserted or upserted, a new Snowflake will be generated for you.

You can also use `Snowflake` or `Sonyflake` as in your Eloquent `$casts` array to have that attribute automatically cast to a Bits instance.

```
use Glhd\Bits\Database\HasSnowflakes;
use Glhd\Bits\Snowflake;
use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    // Auto-generate Snowflake for new models
    use HasSnowflakes;

    // Any attribute can be cast to a `Snowflake` (or `Sonyflake`)
    protected $casts = [
        'id' => Snowflake::class,
    ];
}

$example = Example::create();

$example->id instanceof Snowflake; // true

echo $example->id; // 65898467809951744
```

### Using IDs as timestamps

[](#using-ids-as-timestamps)

One nice property of Snowflakes and Sonyflakes is that they are sortable by time, and can have the timestamp extracted from the ID for later use. This means that if you want to, you can use these IDs in place of a `created_at` timestamp:

```
// Instead of:
User::where('created_at', '>', now());

// You can do (assuming users.id is a snowflake)
User::where('id', '>', app(MakesSnowflakes::class)->firstForTimestamp(now()));
```

```
// Instead of:
$created_at = $user->created_at;

// You can do (assuming User::id is cast to a Snowflake object)
$created_at = $user->id->toCarbon();
```

### Usage with Livewire

[](#usage-with-livewire)

If you're using Livewire, you can use the `SnowflakeSynth` synthesizer to make Snowflakes usable in your components.

All you need to do is to register the synthesizer in your `AppServiceProvider`:

```
use Glhd\Bits\Support\Livewire\SnowflakeSynth;
use Glhd\Bits\Support\Livewire\BitsSynth;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // If only using Snowflakes:
        Livewire::propertySynthesizer(SnowflakeSynth::class);

        // If using Sonyflakes or a custom Bits variant:
        Livewire::propertySynthesizer(BitsSynth::class);
    }
}
```

If you're using a non-Snowflake variant of Bits, you can use the `BitsSynth`instead, which supports any version of Bits at the cost of storing a little more data.

About 64-bit Unique IDs
-----------------------

[](#about-64-bit-unique-ids)

### Snowflake format

[](#snowflake-format)

```
0 0000001100100101110101100110111100101011 01011 01111 000000011101
┳ ━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━ ━━━┳━ ━┳━━━ ━┳━━━━━━━━━━
┗━ unused bit     ┗━ timestamp (41)           ┃   ┃     ┗━ sequence (12)
                              datacenter (5) ━┛   ┗━ worker (5)

```

### Sonyflake format

[](#sonyflake-format)

```
0 000000011001001011101011001101111001010 11010110 1111000000011101
┳ ━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━┳━ ━┳━━━━━━━━━━━━━━
┗━ sign   ┗ timestamp (39)         sequence (8) ┛   ┗ machine (16)

```

Both of these IDs are represented by the same 64-bit integer, `56705782302306333`, but convey different metadata. Depending on your scale and distribution needs, you may find one or the other format preferable, or choose to implement your own custom format.

**Bits** lets generate any kind of 64-bit unique ID you'd like, in the way that makes the most sense for your use-case.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance64

Regular maintenance activity

Popularity52

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.1% 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 ~182 days

Total

14

Last Release

56d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/21592?v=4)[Chris Morrell](/maintainers/inxilpro)[@inxilpro](https://github.com/inxilpro)

---

Top Contributors

[![inxilpro](https://avatars.githubusercontent.com/u/21592?v=4)](https://github.com/inxilpro "inxilpro (82 commits)")[![gehrisandro](https://avatars.githubusercontent.com/u/25097194?v=4)](https://github.com/gehrisandro "gehrisandro (2 commits)")[![rzv-me](https://avatars.githubusercontent.com/u/38325118?v=4)](https://github.com/rzv-me "rzv-me (2 commits)")[![actions-user](https://avatars.githubusercontent.com/u/65916846?v=4)](https://github.com/actions-user "actions-user (1 commits)")[![matthewpaulking](https://avatars.githubusercontent.com/u/32152670?v=4)](https://github.com/matthewpaulking "matthewpaulking (1 commits)")[![rompetomp](https://avatars.githubusercontent.com/u/1550749?v=4)](https://github.com/rompetomp "rompetomp (1 commits)")

---

Tags

laravel

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/glhd-bits/health.svg)

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

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[laravel/horizon

Dashboard and code-driven configuration for Laravel queues.

4.1k84.2M225](/packages/laravel-horizon)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[laravel/cashier-paddle

Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services.

264778.4k3](/packages/laravel-cashier-paddle)

PHPackages © 2026

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