A UUID string is 36 characters; its binary form is 16 bytes. Storing the binary form saves 20 bytes per value (about 55%), at the cost of values that are not readable in database tools.
Model
Use HasBinaryUuids for key generation and BinaryUuidCast so that attributes read as UUID objects instead of raw bytes:
use Illuminate\Database\Eloquent\Model;use Webpatser\LaravelUuid\BinaryUuidCast;use Webpatser\LaravelUuid\HasBinaryUuids; class User extends Model{ use HasBinaryUuids; protected $casts = [ 'id' => BinaryUuidCast::class, 'parent_id' => BinaryUuidCast::class, ]; protected $fillable = ['name', 'email'];} echo $user->id->string; // UUID string, via the cast$user->setUuidFromString($uuid); // sets the key column from a string UUID
By default the trait generates a version 7 UUID and returns its 16 raw bytes from newUniqueId(). If you override newUniqueId(), return bytes (Uuid::v4()->bytes), not a string.
getUuidAsString() and setUuidFromString() take an optional column name and default to the key column. getUuidAsString() returns an empty string when the attribute is not 16 bytes, and setUuidFromString() ignores a string that is not a valid UUID. getUuidAsString() only works on a column that is not cast with BinaryUuidCast; with the cast, use $user->id->string.
Other methods on the trait:
| Method | Returns |
|---|---|
newRandomBinaryUuid() |
Version 4 as 16 bytes |
newOrderedBinaryUuid() |
Version 7 as 16 bytes |
newTimeBasedBinaryUuid() |
Version 1 as 16 bytes |
getUuidVersion(), usesOrderedUuids(), getUuidTimestamp() |
As on HasUuids |
getRouteKey() |
The key as a UUID string |
Warning: In 6.2.1,
getUuidVersion(),usesOrderedUuids(),getUuidTimestamp()andgetRouteKey()throw aTypeErrorwhen the key column also hasBinaryUuidCast. They work only on an uncast binary key.
The cast
BinaryUuidCast accepts a Uuid object, 16 raw bytes, or a 36-character UUID string when you set a value, and stores 16 bytes. When reading it returns a Webpatser\Uuid\Uuid, from either 16 bytes or a 36-character string. Any 16-character string is stored as-is without validation; a value that is neither 16 bytes nor a valid 36-character UUID throws InvalidArgumentException. When the model is serialized (for example to JSON) the cast outputs the UUID string.
Migrations
BinaryUuidMigrations picks the column type for the active database driver:
use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;use Webpatser\LaravelUuid\BinaryUuidMigrations; return new class extends Migration{ public function up() { Schema::create('users', function (Blueprint $table) { BinaryUuidMigrations::addBinaryUuidPrimary($table); BinaryUuidMigrations::addBinaryUuidColumn($table, 'parent_id', nullable: true, index: true); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); }};
| Helper | Signature |
|---|---|
addBinaryUuidPrimary |
(Blueprint $table, string $column = 'id') |
addBinaryUuidColumn |
(Blueprint $table, string $column, bool $nullable = false, bool $index = false) |
addBinaryUuidForeign |
(Blueprint $table, string $column, string $references, bool $nullable = false) |
addBinaryUuidForeign adds a column of the binary type; declare the foreign key constraint yourself with $table->foreign().
| Driver | Column type |
|---|---|
mysql, mariadb |
VARBINARY(16) |
pgsql |
not supported in 6.2.1 (see below) |
sqlite |
blob |
sqlsrv |
not supported in 6.2.1 (see below) |
| other | binary(16) |
Warning: In 6.2.1 the helpers fail on PostgreSQL and SQL Server, because Laravel's grammars have no
byteaoruniqueidentifiercolumn type to resolve. On PostgreSQL use$table->binary('id')->primary(), which gives abyteacolumn. On SQL Server use$table->uuid('id')->primary(), which Laravel maps touniqueidentifier.
When the application is not bootstrapped, the driver falls back to sqlite.
BinaryUuidMigrations::getDatabaseInfo(?string $driver = null) returns an array describing the column type for a driver, and getMigrationStub(string $table, array $columns = []) returns the source of a migration file as a string.
Convert an existing string column
getConversionSql() returns raw SQL for your driver. It does not run anything:
use Webpatser\LaravelUuid\BinaryUuidMigrations; $sql = BinaryUuidMigrations::getConversionSql('users', 'id'); // detected driver$sql = BinaryUuidMigrations::getConversionSql('users', 'id', 'mysql'); // explicit driver
For MySQL and MariaDB it contains these steps, abridged from the generated output (the final drop and rename are commented out in the output):
-- 1. Add temporary binary columnALTER TABLE `users` ADD COLUMN `id_binary` BINARY(16) NULL AFTER `id`; -- 2. Populate binary column from string columnUPDATE `users`SET `id_binary` = UNHEX(REPLACE(`id`, '-', ''))WHERE `id` IS NOT NULL; -- 3. Verify conversion (should return 0)SELECT COUNT(*) FROM `users`WHERE `id` IS NOT NULLAND `id_binary` IS NULL; -- 4. After updating your application code:-- ALTER TABLE `users` DROP COLUMN `id`;-- ALTER TABLE `users` CHANGE `id_binary` `id` BINARY(16) NOT NULL;
The method documents the order: add a binary column, fill it, update the application, drop the string column, rename the binary column. Test it on a copy first.
Str macros
use Illuminate\Support\Str; $binaryUuid = Str::fastBinaryUuid(); // 16 bytes, version 4$orderedBinary = Str::fastBinaryOrderedUuid(); // 16 bytes, version 7 $stringUuid = '550e8400-e29b-41d4-a716-446655440000';$binary = Str::uuidToBinary($stringUuid); // throws InvalidArgumentException when invalid$back = Str::binaryToUuid($binary); // throws when not exactly 16 bytes Str::isValidBinaryUuid($binary); // true
| Macro | Returns |
|---|---|
Str::binaryTimeBasedUuid() |
Version 1 as 16 bytes |
Str::binaryReorderedTimeUuid() |
Version 6 as 16 bytes |
Str::binaryCustomUuid(string $data) |
Version 8 as 16 bytes |
Route model binding
HasBinaryUuids converts a UUID string in the URL to bytes before querying. URL generation through getRouteKey() only works when the key column is not cast with BinaryUuidCast in 6.2.1:
Route::get('/user/{user}', function (User $user) { return view('user.profile', compact('user'));}); // /user/550e8400-e29b-41d4-a716-446655440000
Note: Binary values are not readable in most database tools. Keep the casts on every UUID column, including foreign key columns, so values convert in both directions.
Next steps
- SQL Server: the
uniqueidentifiertype and GUID byte order. - Core UUID documentation: the UUID class API.