{"id":13545576,"url":"https://github.com/spatie/laravel-binary-uuid","last_synced_at":"2026-01-15T04:04:17.551Z","repository":{"id":57056541,"uuid":"110949385","full_name":"spatie/laravel-binary-uuid","owner":"spatie","description":"Optimised binary UUIDs in Laravel","archived":true,"fork":false,"pushed_at":"2018-12-10T09:58:15.000Z","size":325,"stargazers_count":523,"open_issues_count":0,"forks_count":58,"subscribers_count":18,"default_branch":"master","last_synced_at":"2025-11-27T16:34:48.441Z","etag":null,"topics":["laravel","mysql","performance","php","uuid"],"latest_commit_sha":null,"homepage":"https://spatie.be/en/opensource/laravel","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-16T09:12:18.000Z","updated_at":"2025-11-26T15:57:32.000Z","dependencies_parsed_at":"2022-08-24T14:00:36.158Z","dependency_job_id":null,"html_url":"https://github.com/spatie/laravel-binary-uuid","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"purl":"pkg:github/spatie/laravel-binary-uuid","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-binary-uuid","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-binary-uuid/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-binary-uuid/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-binary-uuid/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/laravel-binary-uuid/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-binary-uuid/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28420810,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T10:47:48.104Z","status":"ssl_error","status_checked_at":"2026-01-14T10:46:19.031Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["laravel","mysql","performance","php","uuid"],"created_at":"2024-08-01T11:01:05.978Z","updated_at":"2026-01-15T04:04:17.535Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://www.patreon.com/spatie"],"categories":["PHP"],"sub_categories":[],"readme":"**THIS PACKAGE IS NOT MAINTAINED ANYMORE**\n\nAlternatives: https://github.com/michaeldyrynda/laravel-efficient-uuid \u0026 https://github.com/michaeldyrynda/laravel-model-uuid\n\n# Using optimised binary UUIDs in Laravel\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-binary-uuid.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-binary-uuid)\n[![Build Status](https://img.shields.io/travis/spatie/laravel-binary-uuid/master.svg?style=flat-square)](https://travis-ci.org/spatie/laravel-binary-uuid)\n[![Code coverage](https://scrutinizer-ci.com/g/spatie/laravel-binary-uuid/badges/coverage.png)](https://scrutinizer-ci.com/g/spatie/laravel-binary-uuid)\n[![Quality Score](https://img.shields.io/scrutinizer/g/spatie/laravel-binary-uuid.svg?style=flat-square)](https://scrutinizer-ci.com/g/spatie/laravel-binary-uuid)\n[![StyleCI](https://styleci.io/repos/110949385/shield?branch=master)](https://styleci.io/repos/110949385)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-binary-uuid.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-binary-uuid)\n\nUsing a regular uuid as a primary key is guaranteed to be slow.\n\nThis package solves the performance problem by storing slightly tweaked binary versions of the uuid. You can read more about the storing mechanism here: [http://mysqlserverteam.com/storing-uuid-values-in-mysql-tables/](http://mysqlserverteam.com/storing-uuid-values-in-mysql-tables/).\n\nThe package can generate optimized versions of the uuid. It also provides handy model scopes to easily retrieve models that use binary uuids.\n\nWant to test the perfomance improvements on your system? No problem, we've included [benchmarks](#running-the-benchmarks).\n\nThe package currently only supports MySQL and SQLite.\n\n## Installation\n\nYou can install the package via Composer:\n\n```bash\ncomposer require spatie/laravel-binary-uuid\n```\n\n## Usage\n \nTo let a model make use of optimised UUIDs, you must add a `uuid` field as the primary field in the table.\n\n```php\nSchema::create('table_name', function (Blueprint $table) {\n    $table-\u003euuid('uuid');\n    $table-\u003eprimary('uuid');\n});\n```\n\nTo 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.\n\n```php\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Spatie\\BinaryUuid\\HasBinaryUuid;\n\nclass TestModel extends Model\n{\n    use HasBinaryUuid;\n}\n```\n\nIf don't like the primary key named `uuid` you can manually specify the `getKeyName` method. Don't forget set `$incrementing` to false.\n\n```php\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Spatie\\BinaryUuid\\HasBinaryUuid;\n\nclass TestModel extends Model\n{\n    use HasBinaryUuid;\n\n    public $incrementing = false;\n    \n    public function getKeyName()\n    {\n        return 'custom_uuid';\n    }\n}\n```\n\nIf 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.\n\n```php\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Spatie\\BinaryUuid\\HasBinaryUuid;\n\nclass TestModel extends Model\n{\n    use HasBinaryUuid;\n    \n    /**\n     * The suffix for the uuid text attribute \n     * by default this is '_text'\n     * \n     * @var\n     */\n    protected $uuidSuffix = '_str';\n    \n    /**\n     * The binary UUID attributes that should be converted to text.\n     *\n     * @var array\n     */\n    protected $uuids = [\n        'country_uuid' // foreign or related key\n    ];\n}\n```\n\nIn 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'.\n\nThe `$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.\n\n#### A note on the `uuid` blueprint method\n\nLaravel currently does not allow adding new blueprint methods which can be used out of the box.\nBecause of this, we decided to override the `uuid` behaviour which will create a `BINARY` column instead of a `CHAR(36)` column.\n\nThere are some cases in which Laravel's generated code will also use `uuid`, but does not support our binary implementation.\nAn example are database notifications. \nTo make those work, you'll have to change the migration of those notifications to use `CHAR(36)`.\n\n```php\n// $table-\u003euuid('id')-\u003eprimary();\n\n$table-\u003echar('id', 36)-\u003eprimary();\n```\n\n### Creating a model\n\nThe UUID of a model will automatically be generated upon save.\n\n```php\n$model = MyModel::create();\n\ndump($model-\u003euuid); // b\"\\x11þ╩ÓB#(ªë\\x1FîàÉ\\x1EÝ.\" \n```\n\n### Getting a human-readable UUID\n\nUUIDs are only stored as binary in the database. You can however use a textual version for eg. URL generation.\n\n```php\n$model = MyModel::create();\n\ndump($model-\u003euuid_text); // \"6dae40fa-cae0-11e7-80b6-8c85901eed2e\" \n```\n\nIf you want to set a specific UUID before creating a model, that's also possible.\n\nIt's unlikely though that you'd ever want to do this.\n\n```php\n$model = new MyModel();\n\n$model-\u003euuid_text = $uuid;\n\n$model-\u003esave();\n```\n\n### Querying the model\n\nThe most optimal way to query the database:\n\n```php\n$uuid = 'ff8683dc-cadd-11e7-9547-8c85901eed2e'; // UUID from eg. the URL.\n\n$model = MyModel::withUuid($uuid)-\u003efirst();\n``` \n\nThe `withUuid` scope will automatically encode the UUID string to query the database.\nThe manual approach would be something like this.\n\n```php\n$model = MyModel::where('uuid', MyModel::encodeUuid($uuid))-\u003efirst();\n```\n\nYou can also query for multiple UUIDs using the `withUuid` scope.\n\n```php\n$models = MyModel::withUuid([\n    'ff8683dc-cadd-11e7-9547-8c85901eed2e',\n    'ff8683ab-cadd-11e7-9547-8c85900eed2t',\n])-\u003eget();\n```\n\nNote: Version 1.3.0 added simplified syntax for finding data using a uuid string.\n\n```php\n$uuid = 'ff8683dc-cadd-11e7-9547-8c85901eed2e'; // UUID from eg. the URL.\n\n$model = MyModel::find($uuid);  \n\n$model = MyModel::findOrFail($uuid);\n```\n\nVersion 1.3.0 query for multiple UUIDs.\n\n```php\n$uuids = [\n    'ff8683dc-cadd-11e7-9547-8c85901eed2e',\n    'ff8683ab-cadd-11e7-9547-8c85900eed2t',\n];\n\n$model = MyModel::findMany($uuids);\n``` \n\n#### Querying relations\n\nYou can also use the `withUuid` scope to query relation fields by specifying a field to query.\n\n```php\n$models = MyModel::withUuid('ff8683dc-cadd-11e7-9547-8c85901eed2e', 'relation_field')-\u003eget();\n\n$models = MyModel::withUuid([\n    'ff8683dc-cadd-11e7-9547-8c85901eed2e',\n    'ff8683ab-cadd-11e7-9547-8c85900eed2t',\n], 'relation_field')-\u003eget();\n```\n\n## Running the benchmarks\n\nThe package contains benchmarks that prove storing uuids in a tweaked binary form is really more performant. \n\nBefore running the tests you should set up a MySQL database and specify the connection configuration in `phpunit.xml.dist`.\n\nTo run the tests issue this command.\n```\nphpunit -d memory_limit=-1 --testsuite=benchmarks\n```\n\nRunning the benchmarks can take several minutes. You'll have time for several cups of coffee!\n\n\nWhile 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.\n\nYou may use this data to further investigate the performance of UUIDs in your local machine.\n\nHere are some results for the benchmarks running on our machine.\n\n*A comparison of the normal ID, binary UUID and optimised UUID approach. Optimised UUIDs outperform all other on larger datasets.*\n\n![Comparing different methods](./docs/comparison.png \"Comparing different methods\")\n\n## Testing\n\n``` bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n## Security\n\nIf you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.\n\n## Postcardware\n\nYou'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.\n\nOur address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.\n\nWe publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).\n\n## Credits\n\n- [Brent Roose](https://github.com/brendt)\n- [All Contributors](../../contributors)\n\n## Support us\n\nSpatie 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).\n\nDoes your business depend on our contributions? Reach out and support us on [Patreon](https://www.patreon.com/spatie). \nAll pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-binary-uuid","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Flaravel-binary-uuid","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-binary-uuid/lists"}