~/docs
Resonate
Resonate
9.x 9.0.0, current 8.x 8.0.0 7.x 7.0.1 6.x 6.2.1 5.x 5.1.2 4.x 4.0.2
Laravel UUID
Toggle sidebar
Laravel UUID
webpatser/laravel-uuid 8.0.0
You are reading the 8.x documentation
The current line is 9.x. Read this page for 9.x

Laravel UUID 8.x

Binary Storage

Store UUIDs as 16 bytes with the HasBinaryUuids trait, BinaryUuidCast and the BinaryUuidMigrations helpers.

A UUID is 16 bytes of data. Stored as text it takes 36 characters; stored as binary it takes 16 bytes. The package provides a trait, a cast and migration helpers for binary columns.

Note: Binary values are not readable in database tools. Always go through the trait and cast, or the Str macros below, to convert.

HasBinaryUuids and BinaryUuidCast

use Illuminate\Database\Eloquent\Model;
use Webpatser\LaravelUuid\BinaryUuidCast;
use Webpatser\LaravelUuid\HasBinaryUuids;
 
class User extends Model
{
use HasBinaryUuids;
 
protected $casts = [
'parent_id' => BinaryUuidCast::class,
];
 
protected $fillable = ['name', 'email'];
}
 
$user = User::create(['name' => 'John', 'email' => '[email protected]']);
 
$user->getUuidAsString(); // string form of the key (or pass a column name)
$user->setUuidFromString($uuid); // sets the key column from a string UUID

HasBinaryUuids generates a v7 UUID as 16 raw bytes by default, sets the key type to string, disables incrementing, and converts the key to its string form in getRouteKey(). Route model binding accepts the string UUID in the URL and converts it to binary for the query. This holds when the key column is not cast with BinaryUuidCast (the key attribute stays raw 16 bytes).

Warning: Do not cast the primary key with BinaryUuidCast in 8.0.0. The cast turns the key into a Uuid object, and getUuidAsString(), getRouteKey(), getUuidVersion(), usesOrderedUuids() and getUuidTimestamp() then throw a TypeError. Use the cast on non-key columns such as parent_id.

BinaryUuidCast::get() returns a Webpatser\Uuid\Uuid object. It accepts 16-byte binary values and, as a fallback for mixed storage, 36-character string UUIDs. set() accepts a Uuid object, a 16-byte string or a valid 36-character string, and stores 16 bytes. Anything else throws InvalidArgumentException. When the model is serialized (for example to JSON) the value is the string form.

Other trait helpers:

Method Returns
newUniqueId() v7 as 16 bytes (default key generator)
newRandomBinaryUuid() v4 as 16 bytes
newOrderedBinaryUuid() v7 as 16 bytes
newTimeBasedBinaryUuid() v1 as 16 bytes
getUuidVersion() version of the key, or null
usesOrderedUuids() true when the key is v7
getUuidTimestamp() timestamp for v1, v6 and v7 keys, otherwise null

Migrations

Webpatser\LaravelUuid\BinaryUuidMigrations picks the column type from the connection's driver:

Driver Column type
pgsql bytea
sqlsrv uniqueidentifier
other (MySQL, MariaDB, SQLite) binary(16)

Warning: In 8.0.0 the pgsql and sqlsrv branches 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. On pgsql and sqlsrv, use $table->uuid() or $table->binary() directly.

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(): void
{
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();
});
}
};
Method 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), where $references is 'table.column'. It adds the column but does not create a foreign key constraint in 8.0.0; add $table->foreign(...) yourself
getConversionSql (string $table, string $column, ?string $driver = null): string
getDatabaseInfo (?string $driver = null): array
getMigrationStub (string $table, array $columns = []): string

Converting existing string columns

getConversionSql() returns raw SQL for the driver (mysql, mariadb, pgsql, sqlite, sqlsrv). It adds a {column}_binary column and fills it from the string column. Dropping and renaming the old column are left as commented statements for you to run after your application code is updated.

use Webpatser\LaravelUuid\BinaryUuidMigrations;
 
echo BinaryUuidMigrations::getConversionSql('users', 'id');
echo BinaryUuidMigrations::getConversionSql('users', 'id', 'pgsql');

Warning: The returned SQL is a starting point. Test the whole process on a copy of your data before running it in production.

getDatabaseInfo() returns the column type, storage size and conversion functions for a driver.

Binary Str macros

use Illuminate\Support\Str;
 
$binary = Str::fastBinaryUuid(); // v4, 16 bytes
$ordered = Str::fastBinaryOrderedUuid(); // v7, 16 bytes
 
$binary = Str::uuidToBinary('550e8400-e29b-41d4-a716-446655440000');
$string = Str::binaryToUuid($binary);
 
Str::isValidBinaryUuid($binary); // true
Macro Returns
fastBinaryUuid() v4 as 16 bytes
fastBinaryOrderedUuid() v7 as 16 bytes
binaryTimeBasedUuid() v1 as 16 bytes
binaryReorderedTimeUuid() v6 as 16 bytes
binaryCustomUuid(string $data) v8 as 16 bytes
uuidToBinary(string $uuid) 16 bytes; throws InvalidArgumentException on an invalid UUID
binaryToUuid(string $binary) UUID string; throws InvalidArgumentException unless the input is 16 bytes
isValidBinaryUuid(string $binary) bool

Next steps