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

ActiveLibrary

bluink/laravel-binary-uuid
==========================

Binary support for UUIDs in Laravel

2.1.8-p1(5mo ago)0891MITPHPPHP ^8.1

Since Nov 29Pushed 5mo agoCompare

[ Source](https://github.com/bluinkltd/laravel-binary-uuid)[ Packagist](https://packagist.org/packages/bluink/laravel-binary-uuid)[ Docs](https://github.com/bluinkltd/laravel-binary-uuid)[ RSS](/packages/bluink-laravel-binary-uuid/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (32)Used By (0)

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

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

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 bluink/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 `Spatie\BinaryUuid\HasBinaryUuid` trait.

```
use Illuminate\Database\Eloquent\Model;
use Spatie\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 Spatie\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 Spatie\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.

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

50

—

FairBetter than 96% of packages

Maintenance70

Regular maintenance activity

Popularity16

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

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

Recently: every ~262 days

Total

27

Last Release

173d ago

Major Versions

1.3.2 → 2.1.32020-05-06

PHP version history (3 changes)1.0.0PHP ^7.0

1.1.6PHP ^7.1

2.1PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/8c0a910b17216348ee5ce1da5735b933548d098477e3f130b99c2658ec3138a9?d=identicon)[bluink](/maintainers/bluink)

---

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)")[![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)")[![bluinkltd](https://avatars.githubusercontent.com/u/50176867?v=4)](https://github.com/bluinkltd "bluinkltd (2 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)")[![codebros-nl](https://avatars.githubusercontent.com/u/951675?v=4)](https://github.com/codebros-nl "codebros-nl (1 commits)")[![d1am0nd](https://avatars.githubusercontent.com/u/7977901?v=4)](https://github.com/d1am0nd "d1am0nd (1 commits)")[![dcorrea777](https://avatars.githubusercontent.com/u/7196041?v=4)](https://github.com/dcorrea777 "dcorrea777 (1 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (1 commits)")[![lonnylot](https://avatars.githubusercontent.com/u/656791?v=4)](https://github.com/lonnylot "lonnylot (1 commits)")

---

Tags

laravel-binary-uuidbluink

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k12.2M45](/packages/knuckleswtf-scribe)[grumpydictator/firefly-iii

Firefly III: a personal finances manager.

22.8k69.3k](/packages/grumpydictator-firefly-iii)[laravel/nightwatch

The official Laravel Nightwatch package.

3526.1M13](/packages/laravel-nightwatch)[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11120.2M21](/packages/anourvalar-eloquent-serialize)[firefly-iii/data-importer

Firefly III Data Import Tool.

7545.8k](/packages/firefly-iii-data-importer)[wandesnet/mercadopago-laravel

PHP SDK for integration with Mercado Pago

252.4k](/packages/wandesnet-mercadopago-laravel)

PHPackages © 2026

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