~/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 7.0.1
You are reading the 7.x documentation
The current line is 9.x. Read this page for 9.x

Laravel UUID 7.x

Binary Storage

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

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'];
}
 
$user = User::create(['name' => 'John', 'email' => '[email protected]']);
 
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 BinaryUuidCast in 7.0.1. 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.

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 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 use $table->binary(), which gives a bytea column; on sqlsrv use $table->uuid(), which Laravel maps to uniqueidentifier.

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'): void
BinaryUuidMigrations::addBinaryUuidColumn(Blueprint $table, string $column, bool $nullable = false, bool $index = false): void
BinaryUuidMigrations::getDatabaseInfo(?string $driver = null): array
BinaryUuidMigrations::getConversionSql(string $table, string $column, ?string $driver = null): string
BinaryUuidMigrations::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); // true
strlen($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