UUIDs / ULIDs in Laravel v10

·

2 min read

I remember when I first came across auto-incremented integer values as Primary Key in MySQL. It seem pretty cool then later came across UUIDs and then ULID. For starters, what are UUIDs and ULIDs?

What is a UUID?

UUID stands for Universally Unique Identifier and can also be know as GUID in Microsoft settings. I'm sure you must have come across a combination of strings of this nature 53649e67-2636-4e54-b491-37761f682221. UUIDs are usually consisted of 36character string which are 128bit. UUID are generated from

What is a ULID?

on the other hand, ULID stands for Universally Lexiological Identifier. The significant difference between UUID and ULID is that ULID are sortable and case sensitive.
Some other difference include

  • ULIDs consist of a 48-bit timestamp and a 80-bit random component to make 128bit.

  • They are more suitable and you necessarily dont have to implement integer Primary Key alongside ULID.

Implementing UUID and ULID in Laravel v10

By default, Laravel ships with UUID and ULID from Laravel v9 but integer table ID (PK) are used by default. So use either UUID and ULID. You have to use hasUuids or hasUlids traits on the preferred Model class.

ULID

<?php
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasUlids;
}

UUID

<?php
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasUuids;
}

Writing Migration Files with UUID/ULID

public function up(): void
    {
        Schema::create('administrators', function (Blueprint $table) {
            $table->ulid('id');
            $table->string('firstname');
            $table->rememberToken();
            $table->timestamps();
        });
    }
public function up(): void
    {
        Schema::create('administrators', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('firstname');
            $table->rememberToken();
            $table->timestamps();
        });
    }

If you use sanctum, you'll come across $table->morphs in persona_access_token migration. To use UUID and ULID change:

$table->id();
$table->morphs('tokenable');

//to

$table->ulid();
$table->ulidMorphs('tokenable');

Advantages of UUID/ULID

  • Readability

  • No Predictability (Secure)

  • No Centralized Mode of Generation