A UUID in its text form takes 36 characters. In binary form it takes 16 bytes, 20 bytes less per value. The package provides a trait, a cast, migration helpers and Str macros for the binary form.
HasBinaryUuids
Webpatser\LaravelUuid\HasBinaryUuids generates a version 7 UUID as 16 raw bytes, sets the key type to string, turns off auto-incrementing and resolves route model binding from the text form.
use Illuminate\Database\Eloquent\Model;use Webpatser\LaravelUuid\HasBinaryUuids; class User extends Model{ use HasBinaryUuids; protected $fillable = ['name', 'email'];} echo $user->getUuidAsString(); // "018f4e7c-8b3a-7000-8000-123456789abc"$user->setUuidFromString('550e8400-e29b-41d4-a716-446655440000');
Helper methods on the trait:
| Method | Returns |
|---|---|
getUuidAsString(?string $column = null) |
text form of the key (or of $column), '' when empty |
setUuidFromString(string $uuid, ?string $column = null) |
stores the binary form when the string is valid |
getRouteKey() |
text form, used when building URLs |
newRandomBinaryUuid() |
version 4, 16 bytes |
newOrderedBinaryUuid() |
version 7, 16 bytes |
newTimeBasedBinaryUuid() |
version 1, 16 bytes |
getUuidVersion(), usesOrderedUuids(), getUuidTimestamp() |
same as on HasUuids |
BinaryUuidCast
Webpatser\LaravelUuid\BinaryUuidCast converts between the stored bytes and a Webpatser\Uuid\Uuid object. On read it accepts 16 bytes or a valid 36-character string; on write it accepts a Uuid, 16 bytes or a valid string and stores 16 bytes. Anything else throws InvalidArgumentException. When the model is serialized (for example to JSON), the value becomes the text form.
use Illuminate\Database\Eloquent\Model;use Webpatser\LaravelUuid\BinaryUuidCast; class Event extends Model{ protected $casts = [ 'parent_id' => BinaryUuidCast::class, ];}
Warning: Do not cast the primary key with
BinaryUuidCastin 7.0.1. The cast turns the key into aUuidobject, andgetUuidAsString(),getRouteKey(),getUuidVersion(),usesOrderedUuids()andgetUuidTimestamp()then throw aTypeError. Use the cast on non-key columns such asparent_id.
Migrations
Webpatser\LaravelUuid\BinaryUuidMigrations picks the column type from the current connection's driver:
| Driver | Column type |
|---|---|
| all other drivers (MySQL, MariaDB, SQLite) | $table->binary($column, 16) |
pgsql |
bytea |
sqlsrv |
uniqueidentifier |
If no database connection can be resolved, the helper falls back to the sqlite behavior.
Warning: In 7.0.1 the
pgsqlandsqlsrvbranches add column types (bytea,uniqueidentifier) that Laravel's schema grammar does not know, so the migration fails on those drivers. Only MySQL, MariaDB and SQLite (binary(16)) work. Onpgsqluse$table->binary(), which gives abyteacolumn; onsqlsrvuse$table->uuid(), which Laravel maps touniqueidentifier.
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(); }); }};
Signatures:
BinaryUuidMigrations::addBinaryUuidPrimary(Blueprint $table, string $column = 'id'): voidBinaryUuidMigrations::addBinaryUuidColumn(Blueprint $table, string $column, bool $nullable = false, bool $index = false): voidBinaryUuidMigrations::getDatabaseInfo(?string $driver = null): arrayBinaryUuidMigrations::getConversionSql(string $table, string $column, ?string $driver = null): stringBinaryUuidMigrations::getMigrationStub(string $table, array $columns = []): string
getDatabaseInfo() returns the column type, storage size and conversion functions for a driver. getMigrationStub() returns the source of a complete migration file as a string.
Converting a string column
getConversionSql() returns commented SQL for mysql, mariadb, pgsql, sqlite and sqlsrv. For any other driver it returns the MySQL SQL with a note. The SQL adds a temporary column ({column}_binary, or {column}_guid on sqlsrv), fills it from the text column and gives a verification query; the final steps (drop and rename, or a table rebuild on SQLite) are commented out for you to run after the application code is updated. The library's own docblock warns that data can be lost if this is not handled carefully, so test it on a copy first.
use Webpatser\LaravelUuid\BinaryUuidMigrations; echo BinaryUuidMigrations::getConversionSql('users', 'id', 'mysql');
Str macros for binary values
use Illuminate\Support\Str; $binary = Str::fastBinaryUuid(); // version 4, 16 bytes$ordered = Str::fastBinaryOrderedUuid(); // version 7, 16 bytes$timeBased = Str::binaryTimeBasedUuid(); // version 1$reordered = Str::binaryReorderedTimeUuid(); // version 6$custom = Str::binaryCustomUuid('data'); // version 8 $bytes = Str::uuidToBinary('550e8400-e29b-41d4-a716-446655440000');$string = Str::binaryToUuid($bytes); // "550e8400-e29b-41d4-a716-446655440000" Str::isValidBinaryUuid($bytes); // truestrlen($bytes); // 16
Route model binding
With HasBinaryUuids, the text UUID in the URL is converted to bytes before the query runs, and getRouteKey() converts back when a URL is generated:
Route::get('/user/{user}', function (User $user) { return view('user.profile', compact('user'));}); // /user/550e8400-e29b-41d4-a716-446655440000
Next steps
- SQL Server: the mixed byte order of
uniqueidentifier. - UUID library: the
bytes,stringandhexproperties.