Laravel UUID v6.2.0
SQL Server GUID Integration
SQL Server GUID Support - Laravel UUID v6.2.0
Handle SQL Server's mixed-endianness GUID format seamlessly with automatic byte order correction and native uniqueidentifier
column support in Laravel.
SQL Server GUID Endianness
SQL Server uses mixed-endianness for GUIDs: the first 3 segments are little-endian, while the last 2 are big-endian. This package provides automatic conversion functions to handle this format difference transparently.
GUID Format Conversion
Convert between standard UUID format and SQL Server's GUID format:
use Illuminate\Support\Str; // Import UUID from SQL Server with automatic byte order correction$sqlServerGuid = '825B076B-44EC-E511-80DC-00155D0ABC54'; // From SQL Server$correctedUuid = Str::uuidFromSqlServer($sqlServerGuid); // Standard formatecho $correctedUuid; // '6B075B82-EC44-11E5-80DC-00155D0ABC54' // Export UUID to SQL Server format$standardUuid = '6B075B82-EC44-11E5-80DC-00155D0ABC54';$sqlServerFormat = Str::uuidToSqlServer($standardUuid); // For SQL Serverecho $sqlServerFormat; // '825B076B-44EC-E511-80DC-00155D0ABC54' // Binary SQL Server GUID handling$sqlServerBinary = Str::uuidToSqlServerBinary($standardUuid); // 16-byte SQL Server format$backToString = Str::sqlServerBinaryToUuid($sqlServerBinary); // Convert back to standard // Automatic format detection (optional)if (Str::isSqlServerGuid($someGuid)) { $corrected = Str::uuidFromSqlServer($someGuid);}
Laravel Migration with uniqueidentifier
SQL Server's native uniqueidentifier
columns are automatically supported:
use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Webpatser\LaravelUuid\BinaryUuidMigrations; return new class extends Migration{ public function up() { Schema::create('users', function (Blueprint $table) { // Automatically uses 'uniqueidentifier' on SQL Server // Uses appropriate binary types on other databases BinaryUuidMigrations::addBinaryUuidPrimary($table); BinaryUuidMigrations::addBinaryUuidColumn($table, 'parent_id', true); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); }};
Generated SQL Server Schema
Here's what gets generated for SQL Server:
-- SQL Server - Generated MigrationCREATE TABLE users ( id uniqueidentifier PRIMARY KEY DEFAULT NEWID(), -- Native GUID support parent_id uniqueidentifier NULL, -- 16 bytes native name NVARCHAR(255) NOT NULL, email NVARCHAR(255) NOT NULL UNIQUE, created_at DATETIME2(0) NULL, updated_at DATETIME2(0) NULL); -- Indexes work optimally with uniqueidentifierCREATE INDEX IX_users_parent_id ON users (parent_id);CREATE INDEX IX_users_email ON users (email);
Eloquent Models with SQL Server
Models work transparently with SQL Server's native GUID support:
use Illuminate\Database\Eloquent\Model;use Webpatser\LaravelUuid\HasBinaryUuids;use Webpatser\LaravelUuid\BinaryUuidCast; class User extends Model{ use HasBinaryUuids; // Automatically handles SQL Server uniqueidentifier protected $casts = [ 'id' => BinaryUuidCast::class, // Works with uniqueidentifier 'parent_id' => BinaryUuidCast::class, // Handles NULLs correctly ]; protected $fillable = ['name', 'email']; // Use V7 UUIDs for better clustering in SQL Server public function newUniqueId(): string { return (string) Uuid::v7(); }} // Usage - completely transparentecho $user->id; // Displays as standard UUID format // Route model binding works with string UUIDs in URLsRoute::get('/user/{user}', function (User $user) { // Laravel handles conversion automatically return view('user.profile', compact('user'));});
Cross-Database Compatibility
The same Laravel application can work across different databases:
Database
|
Column Type
|
SQL Server GUIDs
|
Laravel Support
|
---|---|---|---|
SQL Server | uniqueidentifier | ||
MySQL/MariaDB | BINARY(16) | ||
PostgreSQL | bytea | ||
SQLite | BLOB |
Working with Existing SQL Server Data
Handle existing SQL Server databases with GUID columns:
// Reading existing SQL Server GUIDs$users = DB::select("SELECT id, name FROM users WHERE active = 1"); foreach ($users as $user) { // Convert SQL Server GUID to standard UUID if needed $standardUuid = Str::uuidFromSqlServer($user->id); echo "User: {$user->name}, UUID: {$standardUuid}\n";} // Inserting data into SQL Server with proper format$newUserId = Str::fastUuid(); // Standard UUID format$sqlServerGuid = Str::uuidToSqlServer($newUserId); // Convert for SQL Server DB::insert("INSERT INTO users (id, name, email) VALUES (?, ?, ?)", [ $sqlServerGuid, // SQL Server format 'Jane Doe',]);
Stored Procedures and Functions
Use UUIDs with SQL Server stored procedures:
// Call stored procedure with UUID parameter$userId = Str::fastUuid();$sqlServerFormat = Str::uuidToSqlServer($userId); $results = DB::select("EXEC GetUserDetails @UserId = ?", [$sqlServerFormat]); // Handle UUID returns from stored proceduresforeach ($results as $result) { $standardUuid = Str::uuidFromSqlServer($result->user_id); // Process with standard UUID format}
Advanced SQL Server Features
Sequential GUIDs
// Use V7 UUIDs for better SQL Server performance (similar to NEWSEQUENTIALID())class User extends Model{ use HasBinaryUuids; public function newUniqueId(): string { // V7 UUIDs provide chronological ordering like NEWSEQUENTIALID() // but with better randomness and cross-platform compatibility return (string) Uuid::v7(); }}
Full-Text Search with UUIDs
// Convert UUID to string for full-text search$searchUuid = '6B075B82-EC44-11E5-80DC-00155D0ABC54';$sqlServerGuid = Str::uuidToSqlServer($searchUuid); $users = DB::select(" SELECT * FROM users WHERE CONTAINS(*, ?) OR id = ?", ['John', $sqlServerGuid]);
Configuration and Environment
// config/database.php - SQL Server configuration'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '1433'), 'database' => env('DB_DATABASE', 'laravel'), 'username' => env('DB_USERNAME', 'sa'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'prefix_indexes' => true, // SQL Server specific options 'options' => [ PDO::ATTR_STRINGIFY_FETCHES => false, PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8, ],],
Testing SQL Server Integration
use Tests\TestCase;use Illuminate\Foundation\Testing\RefreshDatabase; class SqlServerUuidTest extends TestCase{ use RefreshDatabase; public function test_sql_server_guid_conversion() { $standardUuid = '6B075B82-EC44-11E5-80DC-00155D0ABC54'; $sqlServerGuid = '825B076B-44EC-E511-80DC-00155D0ABC54'; // Test conversion functions $converted = Str::uuidToSqlServer($standardUuid); $this->assertEquals($sqlServerGuid, $converted); $backConverted = Str::uuidFromSqlServer($sqlServerGuid); $this->assertEquals($standardUuid, $backConverted); } public function test_model_with_sql_server() { if (DB::getDriverName() !== 'sqlsrv') { $this->markTestSkipped('SQL Server not available'); } // Verify UUID was created $this->assertTrue(Str::isUuid($user->id)); // Verify it's stored correctly in SQL Server $dbUser = DB::select("SELECT id FROM users WHERE id = ?", [$user->getUuidAsBinary()]); $this->assertCount(1, $dbUser); }}
Benefits of SQL Server Integration
- • Native Support: Uses SQL Server's
uniqueidentifier
type - • Automatic Conversion: Transparent endianness handling
- • Cross-Platform: Same Laravel code works on all databases
- • Zero Performance Impact: Conversion only when using SQL Server methods
- • Lossless Round-Trip: Perfect conversion fidelity