Bhargav Rangani

Bhargav Rangani's Posts

Sr Laravel Developer

UUIDs as Primary Keys with a Trait in Laravel 9

What are UUIDs?

UUIDs stands for Universally Unique Identifiers and are 128 bits values used to uniquely identify some record in our database. UUIDs are represented as a hexadecimal string split into five groups separated by hyphens.UUIDs are universally unique alphanumeric identifiers that are 36 characters long.

Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead.

Updating Migration File

It is a very important step to update our migration file, I want to use the UUIDs in my User class so I will make changes to my User’s migration class.

 $table->id();

to this:

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

If you are using a UUID primary key as a foreign key in another table, you need to change the column type to UUID, where the foreign key is defined. from this:

$table->unsignedBigInteger('user_id')->unsigned();

to this:

$table->uuid('user_id');

Using Trait in Our Model Class

you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model.

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  use HasUuids;

  // ...
}

$user = User::create(['name' => 'John','email' => 'john@doe.com']);

$user->id; //72106479-5367-4853-9b44-b8b7a1e94f01

By default, The HasUuids trait will generate "ordered" UUIDs for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically.

  • UUIDs are safer than using regular numeric IDs because they are not easy to spoof. Regular IDs make it easy to get information about the application, like how many users the application has.
  • Using UUID is a great solution for multi-tenancy applications.

I hope you will find this post useful.

September 20, 20221 minuteBhargav RanganiBhargav Rangani