Skip to content

Primary Keys

The variablePrimaryKey() macro replaces verbose match expressions with a clean, type-safe method for creating primary key columns based on your application’s configuration.

use Cline\VariableKeys\Enums\PrimaryKeyType;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('users', function (Blueprint $table) {
$table->variablePrimaryKey(PrimaryKeyType::ID);
$table->string('name');
$table->timestamps();
});

Traditional sequential numeric IDs. Simplest option but reveals record count and ordering.

$table->variablePrimaryKey(PrimaryKeyType::ID);

Equivalent to:

$table->id();

ULID (Universally Unique Lexicographically Sortable Identifier)

Section titled “ULID (Universally Unique Lexicographically Sortable Identifier)”

26-character case-insensitive strings that are time-ordered and globally unique. Better performance than UUIDs while maintaining sortability.

$table->variablePrimaryKey(PrimaryKeyType::ULID);

Equivalent to:

$table->ulid('id')->primary();

36-character strings (32 hex digits plus 4 hyphens) that are globally unique and cryptographically random. Use when global uniqueness is required without chronological ordering.

$table->variablePrimaryKey(PrimaryKeyType::UUID);

Equivalent to:

$table->uuid('id')->primary();

Specify a custom column name as the second parameter:

$table->variablePrimaryKey(PrimaryKeyType::ULID, 'user_id');

Centralize your primary key type configuration:

config/database.php
return [
'primary_key_type' => env('DB_PRIMARY_KEY_TYPE', 'id'),
];

Then use it in migrations:

use Cline\VariableKeys\Enums\PrimaryKeyType;
$primaryKeyType = PrimaryKeyType::tryFrom(config('database.primary_key_type'))
?? PrimaryKeyType::ID;
Schema::create('users', function (Blueprint $table) use ($primaryKeyType) {
$table->variablePrimaryKey($primaryKeyType);
$table->string('name');
$table->timestamps();
});
TypeUse WhenCharacteristics
IDTraditional apps, simple requirementsSequential, predictable, efficient
ULIDDistributed systems, time-ordered dataSortable, globally unique, URL-safe
UUIDMaximum randomness, global uniquenessCryptographically random, non-sequential
Schema::create('posts', function (Blueprint $table) {
$table->variablePrimaryKey(PrimaryKeyType::ID);
$table->string('title');
$table->text('body');
$table->timestamps();
});
Schema::create('events', function (Blueprint $table) {
$table->variablePrimaryKey(PrimaryKeyType::ULID);
$table->string('type');
$table->json('payload');
$table->timestamps();
});
Schema::create('api_resources', function (Blueprint $table) {
$table->variablePrimaryKey(PrimaryKeyType::UUID);
$table->string('external_id');
$table->json('data');
$table->timestamps();
});