English | العربية | বাংলা | Bosanski | Deutsch | Español | Français | हिन्दी | Italiano | 日本語 | 한국어 | मराठी | Português | Русский | Kiswahili | தமிழ் | తెలుగు | Türkçe | اردو | Tiếng Việt | 中文
- Introduction
- Installation
- Usage
- UUIDv5
- Configuration
- Upgrading
- Support Guidelines
- License - MIT License
Introduction
Database UUIDs lets you use a UUID primary key the way you use an auto-incrementing integer: insert a row without an id, and the database assigns one. Define the key once in a Laravel or Doctrine migration. Inserts from Laravel's query builder, Doctrine DBAL, import scripts, and SQL clients can share the same default by omitting id.
For example, Eloquent's HasUuids trait can assign an ID when you save a customer. A Doctrine entity can do the same in its constructor. Neither runs when a nightly import inserts customers directly. With a database-generated key, the import doesn't need its own UUID generator:
INSERT INTO customers (name) VALUES ('Jane Smith');
Every writer that omits id gets the UUID version you chose in the migration. If you need a primary key before you insert a row, you can still generate one in your application and pass it explicitly.
Key Features
- Generate a UUIDv7 primary key, or choose UUIDv1 or UUIDv4 for a primary key or another column.
- Link related records using UUID foreign keys.
- Give an imported record the same UUIDv5 each time you receive it, using values such as its source and external ID.
Example
To give each customer a UUID, define the primary key in your migration, then leave id out of the insert.
Laravel
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('customers', function (Blueprint $table): void {
$table->primaryUuid();
$table->string('name');
});
Now you can insert a customer using just their name. The database fills in id with a new UUIDv7:
use Illuminate\Support\Facades\DB;
DB::table('customers')->insert(['name' => 'Jane Smith']);
Doctrine
In the up method of a Doctrine migration, create the table on the supplied $schema. Pass the migration's connection to DoctrineUuidSchema so it can choose the right default for your database:
use DefectiveCode\DatabaseUuids\Doctrine\DoctrineUuidSchema;
use DefectiveCode\DatabaseUuids\UuidDefaults;
use Doctrine\DBAL\Types\Types;
$uuids = new DoctrineUuidSchema($this->connection, new UuidDefaults);
$customers = $schema->createTable('customers');
$uuids->primaryUuid($customers);
$customers->addColumn('name', Types::STRING);
After the migration runs, insert the customer using your DBAL connection. The database assigns the UUIDv7:
$connection->insert('customers', ['name' => 'Jane Smith']);
Installation
You can install Database UUIDs using Composer:
composer require defectivecode/database-uuids
If you're starting a standalone Doctrine application, install DBAL and Doctrine Migrations alongside the package:
composer require defectivecode/database-uuids 'doctrine/dbal:^4.4' 'doctrine/migrations:^3.9'
Requirements
Database UUIDs requires PHP 8.5 or later. For Laravel migrations, use Laravel 13. For Doctrine migrations, use Doctrine DBAL 4.4 or later in the 4.x series.
Supported Databases
| Database | UUID column | What you need to know |
|---|---|---|
| PostgreSQL 18+ | uuid |
UUIDv4 and UUIDv7 work out of the box. For UUIDv1 and UUIDv5, enable uuid-ossp. |
| MySQL 8.4 | char(36) |
If you replicate writes, use row-based replication so replicas receive the UUID generated on the primary. |
| MariaDB 11.7+ | uuid |
Use the mariadb driver in Laravel. Doctrine detects MariaDB when you connect with pdo_mysql. |
| SQL Server 2022 | uniqueidentifier |
SQL Server sorts UUIDs differently from their byte order. Don't rely on sorting a UUIDv7 column by creation time. |
| SQLite | Text affinity | Use a UTF-8 database. Only UUIDv5 requires the SHA-1 extension. |
UUIDv7 embeds a UTC timestamp with millisecond precision. The inline defaults on MySQL, SQL Server, and SQLite don't guarantee generation order within the same millisecond.
On SQLite, define columns with UUID defaults when creating the table. To add one to an existing table, rebuild it: ALTER TABLE ADD COLUMN can't add a column with a non-constant default.
Usage
Laravel Migrations
Laravel registers the package's schema methods automatically. Use primaryUuid for the table's primary key and generatedUuid for any other column the database should fill in. Both methods generate UUIDv7 by default. To use UUIDv1 or UUIDv4, pass the version you want:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('customers', function (Blueprint $table): void {
$table->primaryUuid();
$table->generatedUuid('public_id', version: 4);
$table->string('name');
$table->timestamps();
});
Saving an Eloquent Model
With the default in place, the Customer model doesn't need HasUuids or a creating callback to assign an ID. Tell Eloquent the key is a non-incrementing string:
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public $incrementing = false;
protected $keyType = 'string';
}
Save the customer without assigning either UUID. The database fills in id and public_id, just as it would for the SQL insert above:
$customer = new Customer;
$customer->name = 'Jane Smith';
$customer->save();
There is one difference from Eloquent's usual incrementing key: with $incrementing = false, save() doesn't fetch the generated ID. If you need the key to create a related row, retrieve it as part of the insert where your database supports RETURNING, or look up the row by a unique business key.
Defining Foreign Keys
Suppose each order belongs to a customer. The order needs a new ID of its own, but its customer_id must hold the ID of an existing customer. Use Laravel's foreignUuid method for that column and call constrained to reference customers.id:
Schema::create('orders', function (Blueprint $table): void {
$table->primaryUuid();
$table->foreignUuid('customer_id')->constrained();
});
When rolling back this migration, drop orders before customers so the foreign key no longer references the table you are dropping.
If your column name doesn't follow Laravel's conventions, pass the referenced table to constrained. In this example, deleting the reviewer sets reviewer_id to null. Call nullable before constrained:
Schema::table('orders', function (Blueprint $table): void {
$table->foreignUuid('reviewer_id')
->nullable()
->constrained('customers')
->nullOnDelete();
});
If the customer's key is named customer_uuid, pass it as the second argument: constrained('customers', 'customer_uuid'). You can also let Laravel read the table and key names from the model:
use App\Models\Customer;
$table->foreignUuidFor(Customer::class, 'billing_customer_id')->constrained();
Use foreignUuidFor when you want a UUID column. If you already use foreignIdFor, it chooses a UUID column for a model with a string key unless the model uses ULIDs. For a UUID that doesn't reference a model, such as a request ID supplied by your application, use $table->uuid('request_id').
Defining Polymorphic Relationships
An attachment might belong to a customer or an order. Use uuidMorphs to store the related model's type and UUID together. If the relationship is optional, use nullableUuidMorphs:
Schema::create('attachments', function (Blueprint $table): void {
$table->primaryUuid();
$table->uuidMorphs('attachable');
$table->nullableUuidMorphs('reviewer');
});
Here, uuidMorphs('attachable') creates attachable_type, attachable_id, and an index on the pair. There is no foreign key constraint since the related records can live in different tables.
Doctrine Migrations
To create the customers and orders tables in a Doctrine migration, use DoctrineUuidSchema in your up method. Pass it the migration's connection so it chooses the correct UUID type for your database:
use DefectiveCode\DatabaseUuids\Doctrine\DoctrineUuidSchema;
use DefectiveCode\DatabaseUuids\UuidDefaults;
use Doctrine\DBAL\Types\Types;
$uuids = new DoctrineUuidSchema($this->connection, new UuidDefaults);
$customers = $schema->createTable('customers');
$uuids->primaryUuid($customers);
$uuids->generatedUuid($customers, 'public_id', version: 4);
$customers->addColumn('name', Types::STRING);
$orders = $schema->createTable('orders');
$uuids->primaryUuid($orders);
$uuids->foreignUuid($orders, 'customer_id', 'customers');
Using a Generated Key in a Related Row
Suppose you want to create a customer and their first order. On PostgreSQL and SQLite, use RETURNING id to get the UUID from the insert itself. Pass that value to the order as customer_id and let the database assign the order's own primary key:
$customerId = $connection->fetchOne(
'INSERT INTO customers (name) VALUES (?) RETURNING id',
['Jane Smith'],
);
$connection->insert('orders', ['customer_id' => $customerId]);
This example uses DBAL directly. It doesn't construct an entity or call a prePersist listener. If you also write through Doctrine ORM, configure the entity's ID mapping separately. A database default alone doesn't tell the ORM to omit the ID or how to retrieve it after flush().
Storing UUIDs and Referencing Other Tables
Use uuid to store a UUID your application already has, such as a request ID. Use foreignUuid when the database should also check that a related row exists. For example, to keep an order when its reviewer is deleted, make the column nullable and set the onDelete option to SET NULL:
$uuids->uuid($orders, 'request_id', nullable: true);
$uuids->foreignUuid(
$orders,
'reviewer_id',
'customers',
foreignColumn: 'id',
nullable: true,
options: ['onDelete' => 'SET NULL'],
);
For a polymorphic relationship, define the type and UUID columns yourself and index them together:
$attachments = $schema->createTable('attachments');
$uuids->primaryUuid($attachments);
$attachments->addColumn('attachable_type', Types::STRING);
$uuids->uuid($attachments, 'attachable_id');
$attachments->addIndex(['attachable_type', 'attachable_id']);
Rolling Back a Migration
To roll back the customers and orders migration, use addSql in your down method. Dropping orders first removes the foreign key before you drop customers. This order matters on SQLite when the tables contain data and foreign keys are enabled:
public function down(Schema $schema): void
{
$this->addSql('DROP TABLE orders');
$this->addSql('DROP TABLE customers');
}
Inspecting Existing Tables
On MariaDB, DBAL needs to know that the database type uuid maps to its guid type. DoctrineUuidSchema registers this mapping if it isn't already set. If a tool such as Doctrine Migrations inspects tables before your helper runs, register the mapping on the connection instead. With DoctrineBundle, set mapping_types: { uuid: guid }.
On SQLite, DBAL doesn't always recognize the UUID default or generated column it originally created. It may suggest rebuilding a table even though you haven't changed it. Write migrations for these columns explicitly, and review the SQL before applying a generated migration.
UUIDv5
Generating a UUID from Source Columns
Suppose you import customers from a CRM. Each customer has an ID in the CRM, and you want to recognize that customer the next time you import them. A UUIDv5 gives you the same UUID for the same namespace and name.
Use generatedUuidV5 to build the name from one or more columns. Here, source_uuid is derived from the source system and its customer ID. If you update external_id on the row, the database recalculates source_uuid. The primary key stays the same, so foreign keys that reference it remain valid.
Importing with Laravel
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('imported_customers', function (Blueprint $table): void {
$table->primaryUuid();
$table->string('source_system', 64);
$table->string('external_id', 128);
$table->string('name');
$table->unique(['source_system', 'external_id']);
$table->generatedUuidV5(
'source_uuid',
namespace: 'd66b0185-e157-4f78-b87e-cb9119cafeb4',
from: ['source_system', 'external_id'],
)->unique();
});
To import a customer, pass the source values and let the database fill in both UUIDs. Match on source_system and external_id, the same columns you marked as unique in the migration:
use Illuminate\Support\Facades\DB;
DB::table('imported_customers')->upsert(
['source_system' => 'crm', 'external_id' => '12345', 'name' => 'Jane Smith'],
['source_system', 'external_id'],
['name'],
);
If the CRM sends customer 12345 again with a new name, the upsert updates name and keeps both UUIDs. Use the source columns as the match key on SQL Server as well: both values are present in the incoming record, while source_uuid is generated only in the database.
Importing with Doctrine
To track the same imports in Doctrine, create imported_customers in your migration's up method. Give the source columns a unique constraint so that each customer appears only once per source system:
use DefectiveCode\DatabaseUuids\Doctrine\DoctrineUuidSchema;
use DefectiveCode\DatabaseUuids\UuidDefaults;
use Doctrine\DBAL\Types\Types;
$uuids = new DoctrineUuidSchema($this->connection, new UuidDefaults);
$customers = $schema->createTable('imported_customers');
$uuids->primaryUuid($customers);
$customers->addColumn('source_system', Types::STRING, ['length' => 64]);
$customers->addColumn('external_id', Types::STRING, ['length' => 128]);
$customers->addColumn('name', Types::STRING);
$customers->addUniqueConstraint(['source_system', 'external_id']);
$uuids->generatedUuidV5(
$customers,
'source_uuid',
namespace: 'd66b0185-e157-4f78-b87e-cb9119cafeb4',
from: ['source_system', 'external_id'],
);
$customers->addUniqueConstraint(['source_uuid']);
Use addUniqueConstraint here rather than addUniqueIndex. On SQL Server, DBAL adds a filter to the unique index, and SQL Server doesn't allow that filter on a computed column.
For repeat imports, execute your database's upsert statement through DBAL. On PostgreSQL and SQLite, use ON CONFLICT. Bind the source values and name; leave both UUID columns to the database:
$sql = <<<'SQL'
INSERT INTO imported_customers (source_system, external_id, name)
VALUES (?, ?, ?)
ON CONFLICT (source_system, external_id) DO UPDATE SET name = excluded.name
SQL;
$connection->executeStatement($sql, ['crm', '12345', 'Jane Smith']);
$connection->executeStatement($sql, ['crm', '12345', 'Jane Jones']);
The second import updates the customer's name without replacing either UUID. To read the generated values, fetch the row by its source keys:
$customer = $connection->fetchAssociative(
'SELECT id, source_uuid, name FROM imported_customers WHERE source_system = ? AND external_id = ?',
['crm', '12345'],
);
Choosing Source Values
Choose non-null, variable-length text columns and use UTF-8. With one source column, its value is the UUIDv5 name. With several columns, the package prefixes each value with its UTF-8 byte length and a colon, then joins the values in the order you listed. For example, crm and 12345 become 3:crm5:12345. To reproduce the UUID elsewhere, use that exact name and the same namespace.
Generating a UUID from a Name
You can also generate a UUIDv5 without saving a record. For example, to look up the UUID from the import above on PostgreSQL, use makeV5 to get the query for that database. Bind the namespace first, followed by the name:
use DefectiveCode\DatabaseUuids\UuidDefaults;
use Illuminate\Support\Facades\DB;
$namespace = 'd66b0185-e157-4f78-b87e-cb9119cafeb4';
$sql = (new UuidDefaults)->makeV5('pgsql')->selectSql();
$id = DB::connection('pgsql')->scalar($sql, [$namespace, '3:crm5:12345']);
With Doctrine DBAL, use fetchOne on the connection. For example, on SQLite with the SHA-1 extension loaded, this gives you the same UUID as the imported row's source_uuid:
use DefectiveCode\DatabaseUuids\UuidDefaults;
$namespace = 'd66b0185-e157-4f78-b87e-cb9119cafeb4';
$sql = (new UuidDefaults)->makeV5('sqlite')->selectSql();
$id = $connection->fetchOne($sql, [$namespace, '3:crm5:12345']);
When using MariaDB, pass mariadb to makeV5, even if your DBAL connection uses pdo_mysql.
Configuration
PostgreSQL UUIDv1 and UUIDv5
PostgreSQL 18 can generate UUIDv4 and UUIDv7 without an extension. If your migration uses UUIDv1 or UUIDv5, enable the uuid-ossp extension in your database first:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Include the schema where you installed the extension in the connection's search path. If you use a managed database, check that it allows uuid-ossp and that the role running the migration can enable it.
SQLite UUIDv5
SQLite needs the SHA-1 extension to generate UUIDv5 values. Database UUIDs doesn't include a compiled extension. You can use a build for your platform or compile sha1.c yourself. On Linux, with the SQLite development headers installed, run:
cc -shared -fPIC sha1.c -o sha1.so
SQLite loads extensions per connection. Use Pdo\Sqlite::loadExtension() on the connection that runs the migration, before it creates the generated column. Load the extension on each connection that writes to the table or runs a UUIDv5 query, including connections opened by import scripts and command-line tools.
If you're adding a stored UUIDv5 column to an existing SQLite table, rebuild the table with the column in its definition. SQLite can't add a stored generated column with ALTER TABLE.
Upgrading
Updating the Composer package doesn't change how an existing table generates UUIDs. To use a new default, write a migration that updates the affected columns. Keep existing IDs so foreign keys still point to the same rows. The new default applies to future inserts that omit the ID. On SQLite, you may need to rebuild the table to change the default.
If a custom default calls a shared routine, install the routine before creating columns that reference it and roll back those columns before uninstalling it. SqlScript passes each entry unchanged to your $execute callback: use $connection->statement(...) in a Laravel migration or $this->addSql(...) in a Doctrine migration. Put each SQL Server batch in its own entry without the CLI delimiter GO.
Pin both revisions when upgrading a shared routine. With $upgrade = $newRevision->replacing($oldRevision), call $upgrade->install($execute) in up() to apply the new revision and $upgrade->uninstall($execute) in down() to rerun the old revision's install SQL. Both definitions need to be safe to apply over one another.
Before changing a generated UUIDv5 column, check where you use its values. Changing the namespace, the source columns, or their order can give existing rows different UUIDs. Include any records or external systems that reference those UUIDs in your migration plan.
Support Guidelines
Thanks for choosing our open source package! Please take a moment to check out these support guidelines. They'll help you get the most out of our project.
Community Driven Support
Our open-source project is fueled by our awesome community. If you have questions or need assistance, StackOverflow and other online resources are your best bets.
Bugs, and Feature Prioritization
The reality of managing an open-source project means we can't address every reported bug or feature request immediately. We prioritize issues in the following order:
1. Bugs Affecting Our Paid Products
Bugs that impact our paid products will always be our top priority. In some cases, we may only address bugs that affect us directly.
2. Community Pull Requests
If you've identified a bug and have a solution, please submit a pull request. After issues affecting our products, we give the next highest priority to these community-driven fixes. Once reviewed and approved, we'll merge your solution and credit your contribution.
3. Financial Support
For issues outside the mentioned categories, you can opt to fund their resolution. Each open issue is linked to an order form where you can contribute financially. We prioritize these issues based on the funding amount provided.
Community Contributions
Open source thrives when its community is active. Even if you're not fixing bugs, consider contributing through code improvements, documentation updates, tutorials, or by assisting others in community channels. We highly encourage everyone, as a community, to help support open-source work.
To reiterate, DefectiveCode will prioritize bugs based on how they impact our paid products, community pull requests, and the financial support received for issues.
License - MIT License
Copyright © Defective Code, LLC. All rights reserved
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.