PHPackages                             boxed-code/laravel-binary-uuid - 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. boxed-code/laravel-binary-uuid

ActiveLibrary

boxed-code/laravel-binary-uuid
==============================

Binary support for UUIDs in Laravel

2.0.1(5y ago)08.8k↓39.5%MITPHPPHP ^7.2|^8.0

Since Nov 29Pushed 1y agoCompare

[ Source](https://github.com/boxed-code/laravel-binary-uuid)[ Packagist](https://packagist.org/packages/boxed-code/laravel-binary-uuid)[ Docs](https://github.com/boxed-code/laravel-binary-uuid)[ RSS](/packages/boxed-code-laravel-binary-uuid/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (19)Used By (0)

Using optimised binary UUIDs in Laravel
=======================================

[](#using-optimised-binary-uuids-in-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/317be4165b829cbb3a93327fddd8127e1aa40c60df6860a969160ee3dc068aef/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f626f7865642d636f64652f6c61726176656c2d62696e6172792d757569642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/boxed-code/laravel-binary-uuid)[![Tests](https://github.com/boxed-code/laravel-binary-uuid/actions/workflows/run_tests.yml/badge.svg)](https://github.com/boxed-code/laravel-binary-uuid/actions/workflows/run_tests.yml)[![StyleCI](https://camo.githubusercontent.com/8831b1812e2b47d3704901347dad3944b3a64b22fabe1ab119e2db7f95863faf/68747470733a2f2f7374796c6563692e696f2f7265706f732f3131303934393338352f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/110949385)

*Forked from the [archived package](https://github.com/spatie/laravel-binary-uuid) at spaite, maintenance releases only.*

Using a regular uuid as a primary key is guaranteed to be slow.

This package solves the performance problem by storing slightly tweaked binary versions of the uuid. You can read more about the storing mechanism here: .

The package can generate optimized versions of the uuid. It also provides handy model scopes to easily retrieve models that use binary uuids.

Want to test the perfomance improvements on your system? No problem, we've included [benchmarks](#running-the-benchmarks).

The package currently only supports MySQL and SQLite.

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

[](#installation)

You can install the package via Composer:

```
composer require boxed-code/laravel-binary-uuid
```

Usage
-----

[](#usage)

To let a model make use of optimised UUIDs, you must add a `uuid` field as the primary field in the table.

```
Schema::create('table_name', function (Blueprint $table) {
    $table->uuid('uuid');
    $table->primary('uuid');
});
```

To get your model to work with the encoded UUID (i.e. to use uuid as a primary key), you must let your model use the `BoxedCode\BinaryUuid\HasBinaryUuid` trait.

```
use Illuminate\Database\Eloquent\Model;
use BoxedCode\BinaryUuid\HasBinaryUuid;

class TestModel extends Model
{
    use HasBinaryUuid;
}
```

If don't like the primary key named `uuid` you can manually specify the `getKeyName` method. Don't forget set `$incrementing` to false.

```
use Illuminate\Database\Eloquent\Model;
use BoxedCode\BinaryUuid\HasBinaryUuid;

class TestModel extends Model
{
    use HasBinaryUuid;

    public $incrementing = false;

    public function getKeyName()
    {
        return 'custom_uuid';
    }
}
```

If you try converting your model to JSON with binary attributes, you will see errors. By declaring your binary attributes in `$uuidAttributes` on your model, you will tell the package to cast those UUID's to text whenever they are converted to array. Also, this adds a dynamic accessor for each of the uuid attributes.

```
use Illuminate\Database\Eloquent\Model;
use BoxedCode\BinaryUuid\HasBinaryUuid;

class TestModel extends Model
{
    use HasBinaryUuid;

    /**
     * The suffix for the uuid text attribute
     * by default this is '_text'
     *
     * @var
     */
    protected $uuidSuffix = '_str';

    /**
     * The binary UUID attributes that should be converted to text.
     *
     * @var array
     */
    protected $uuids = [
        'country_uuid' // foreign or related key
    ];
}
```

In your JSON you will see `uuid` and `country_uuid` in their textual representation. If you're also making use of composite primary keys, the above works well enough too. Just include your keys in the `$uuids` array or override the `getKeyName()` method on your model and return your composite primary keys as an array of keys. You can also customize the UUID text attribute suffix name. In the code above, instead of '\_text' it's '\_str'.

The `$uuids` array in your model defines fields that will be converted to uuid strings when retrieved and converted to binary when written to the database. You do not need to define these fields in the `$casts` array in your model.

#### A note on the `uuid` blueprint method

[](#a-note-on-the-uuid-blueprint-method)

Laravel currently does not allow adding new blueprint methods which can be used out of the box. Because of this, we decided to override the `uuid` behaviour which will create a `BINARY` column instead of a `CHAR(36)` column.

There are some cases in which Laravel's generated code will also use `uuid`, but does not support our binary implementation. An example are database notifications. To make those work, you'll have to change the migration of those notifications to use `CHAR(36)`.

```
// $table->uuid('id')->primary();

$table->char('id', 36)->primary();
```

### Creating a model

[](#creating-a-model)

The UUID of a model will automatically be generated upon save.

```
$model = MyModel::create();

dump($model->uuid); // b"\x11þ╩ÓB#(ªë\x1FîàÉ\x1EÝ."
```

### Getting a human-readable UUID

[](#getting-a-human-readable-uuid)

UUIDs are only stored as binary in the database. You can however use a textual version for eg. URL generation.

```
$model = MyModel::create();

dump($model->uuid_text); // "6dae40fa-cae0-11e7-80b6-8c85901eed2e"
```

If you want to set a specific UUID before creating a model, that's also possible.

It's unlikely though that you'd ever want to do this.

```
$model = new MyModel();

$model->uuid_text = $uuid;

$model->save();
```

### Querying the model

[](#querying-the-model)

The most optimal way to query the database:

```
$uuid = 'ff8683dc-cadd-11e7-9547-8c85901eed2e'; // UUID from eg. the URL.

$model = MyModel::withUuid($uuid)->first();
```

The `withUuid` scope will automatically encode the UUID string to query the database. The manual approach would be something like this.

```
$model = MyModel::where('uuid', MyModel::encodeUuid($uuid))->first();
```

You can also query for multiple UUIDs using the `withUuid` scope.

```
$models = MyModel::withUuid([
    'ff8683dc-cadd-11e7-9547-8c85901eed2e',
    'ff8683ab-cadd-11e7-9547-8c85900eed2t',
])->get();
```

Note: Version 1.3.0 added simplified syntax for finding data using a uuid string.

```
$uuid = 'ff8683dc-cadd-11e7-9547-8c85901eed2e'; // UUID from eg. the URL.

$model = MyModel::find($uuid);

$model = MyModel::findOrFail($uuid);
```

Version 1.3.0 query for multiple UUIDs.

```
$uuids = [
    'ff8683dc-cadd-11e7-9547-8c85901eed2e',
    'ff8683ab-cadd-11e7-9547-8c85900eed2t',
];

$model = MyModel::findMany($uuids);
```

#### Querying relations

[](#querying-relations)

You can also use the `withUuid` scope to query relation fields by specifying a field to query.

```
$models = MyModel::withUuid('ff8683dc-cadd-11e7-9547-8c85901eed2e', 'relation_field')->get();

$models = MyModel::withUuid([
    'ff8683dc-cadd-11e7-9547-8c85901eed2e',
    'ff8683ab-cadd-11e7-9547-8c85900eed2t',
], 'relation_field')->get();
```

Running the benchmarks
----------------------

[](#running-the-benchmarks)

The package contains benchmarks that prove storing uuids in a tweaked binary form is really more performant.

Before running the tests you should set up a MySQL database and specify the connection configuration in `phpunit.xml.dist`.

To run the tests issue this command.

```
phpunit -d memory_limit=-1 --testsuite=benchmarks

```

Running the benchmarks can take several minutes. You'll have time for several cups of coffee!

While the test are running average results are outputted in the terminal. After the tests are complete you'll find individual query stats as CSV files in the test folder.

You may use this data to further investigate the performance of UUIDs in your local machine.

Here are some results for the benchmarks running on our machine.

*A comparison of the normal ID, binary UUID and optimised UUID approach. Optimised UUIDs outperform all other on larger datasets.*

[![Comparing different methods](./docs/comparison.png "Comparing different methods")](./docs/comparison.png)

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Brent Roose](https://github.com/brendt)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance33

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~69 days

Recently: every ~228 days

Total

18

Last Release

1914d ago

Major Versions

1.2.0 → v2.x-dev2018-08-08

1.3.0 → 2.02021-02-19

PHP version history (3 changes)1.0.0PHP ^7.0

1.1.6PHP ^7.1

2.0PHP ^7.2|^8.0

### Community

Maintainers

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

---

Top Contributors

[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (86 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (47 commits)")[![vpratfr](https://avatars.githubusercontent.com/u/2526465?v=4)](https://github.com/vpratfr "vpratfr (23 commits)")[![isocroft](https://avatars.githubusercontent.com/u/5495952?v=4)](https://github.com/isocroft "isocroft (22 commits)")[![slashequip](https://avatars.githubusercontent.com/u/2316916?v=4)](https://github.com/slashequip "slashequip (8 commits)")[![faustbrian](https://avatars.githubusercontent.com/u/22145591?v=4)](https://github.com/faustbrian "faustbrian (4 commits)")[![olsgreen](https://avatars.githubusercontent.com/u/1324164?v=4)](https://github.com/olsgreen "olsgreen (4 commits)")[![tvbeek](https://avatars.githubusercontent.com/u/2026498?v=4)](https://github.com/tvbeek "tvbeek (3 commits)")[![louisl](https://avatars.githubusercontent.com/u/1140394?v=4)](https://github.com/louisl "louisl (2 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (1 commits)")[![dcorrea777](https://avatars.githubusercontent.com/u/7196041?v=4)](https://github.com/dcorrea777 "dcorrea777 (1 commits)")[![fduchateau](https://avatars.githubusercontent.com/u/16178427?v=4)](https://github.com/fduchateau "fduchateau (1 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (1 commits)")[![lonnylot](https://avatars.githubusercontent.com/u/656791?v=4)](https://github.com/lonnylot "lonnylot (1 commits)")[![d1am0nd](https://avatars.githubusercontent.com/u/7977901?v=4)](https://github.com/d1am0nd "d1am0nd (1 commits)")

---

Tags

spatielaravel-binary-uuid

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/boxed-code-laravel-binary-uuid/health.svg)

```
[![Health](https://phpackages.com/badges/boxed-code-laravel-binary-uuid/health.svg)](https://phpackages.com/packages/boxed-code-laravel-binary-uuid)
```

###  Alternatives

[laravel/horizon

Dashboard and code-driven configuration for Laravel queues.

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

Easily debug Laravel apps

31738.4M2.8k](/packages/spatie-laravel-ray)[spatie/ray

Debug with Ray to fix problems faster

62242.5M758](/packages/spatie-ray)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[spatie/laravel-webhook-server

Send webhooks in Laravel apps

1.1k8.8M22](/packages/spatie-laravel-webhook-server)[sassnowski/venture

A package to manage complex workflows built on top of Laravel's queue.

825254.5k1](/packages/sassnowski-venture)

PHPackages © 2026

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