PHPackages                             spatie/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. [Utility &amp; Helpers](/categories/utility)
4. /
5. spatie/laravel-binary-uuid

Abandoned → [https://github.com/michaeldyrynda/laravel-efficient-uuid](/?search=https%3A%2F%2Fgithub.com%2Fmichaeldyrynda%2Flaravel-efficient-uuid)ArchivedLibrary[Utility &amp; Helpers](/categories/utility)

spatie/laravel-binary-uuid
==========================

Binary support for UUIDs in Laravel

1.3.0(7y ago)52066.5k57MITPHPPHP ^7.1

Since Nov 29Pushed 7y ago18 watchersCompare

[ Source](https://github.com/spatie/laravel-binary-uuid)[ Packagist](https://packagist.org/packages/spatie/laravel-binary-uuid)[ Docs](https://github.com/spatie/laravel-binary-uuid)[ RSS](/packages/spatie-laravel-binary-uuid/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (4)Versions (17)Used By (0)

**THIS PACKAGE IS NOT MAINTAINED ANYMORE**

Alternatives:  &amp;

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

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

[![Latest Version on Packagist](https://camo.githubusercontent.com/ce6a52735bce03dbcceb4c1855e714d4d506be3ff337bd8392692a108120717c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d62696e6172792d757569642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-binary-uuid)[![Build Status](https://camo.githubusercontent.com/1d7ebc4e7a6cdba08cefa546fa8841b8a84ad891719c2cf1f1962cad561032e1/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7370617469652f6c61726176656c2d62696e6172792d757569642f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/spatie/laravel-binary-uuid)[![Code coverage](https://camo.githubusercontent.com/e6ab41ce509beb9f4204d503e0f7cf73f523d681990d40f207e1712b6e03efb0/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7370617469652f6c61726176656c2d62696e6172792d757569642f6261646765732f636f7665726167652e706e67)](https://scrutinizer-ci.com/g/spatie/laravel-binary-uuid)[![Quality Score](https://camo.githubusercontent.com/966f90b3673ea3a7f408a37bc65f1c69fcf9434e0f595c1c16eb98a688a5d6de/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f6c61726176656c2d62696e6172792d757569642e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/laravel-binary-uuid)[![StyleCI](https://camo.githubusercontent.com/8831b1812e2b47d3704901347dad3944b3a64b22fabe1ab119e2db7f95863faf/68747470733a2f2f7374796c6563692e696f2f7265706f732f3131303934393338352f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/110949385)[![Total Downloads](https://camo.githubusercontent.com/b172e38c8a35a34ebf00378695046e9fa00c3882ea0467d88181020eccd5c9b3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d62696e6172792d757569642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-binary-uuid)

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 spatie/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.

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.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

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

Support us
----------

[](#support-us)

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Does your business depend on our contributions? Reach out and support us on [Patreon](https://www.patreon.com/spatie). All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License
-------

[](#license)

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

###  Health Score

43

↑

FairBetter than 91% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity48

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity66

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

Recently: every ~11 days

Total

16

Last Release

2736d ago

Major Versions

1.2.0 → v2.x-dev2018-08-08

PHP version history (2 changes)1.0.0PHP ^7.0

1.1.6PHP ^7.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

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)")[![d1am0nd](https://avatars.githubusercontent.com/u/7977901?v=4)](https://github.com/d1am0nd "d1am0nd (1 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)")

---

Tags

laravelmysqlperformancephpuuidspatielaravel-binary-uuid

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-package-tools

Tools for creating Laravel packages

933119.8M5.7k](/packages/spatie-laravel-package-tools)[spatie/laravel-data

Create unified resources and data transfer objects

1.7k27.1M477](/packages/spatie-laravel-data)[spatie/macroable

A trait to dynamically add methods to a class

72758.1M59](/packages/spatie-macroable)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k16.2M46](/packages/spatie-regex)[spatie/laravel-collection-macros

A set of useful Laravel collection macros

1.9k5.5M21](/packages/spatie-laravel-collection-macros)[spatie/enum

PHP Enums

84128.0M60](/packages/spatie-enum)

PHPackages © 2026

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