UUIDs in Laravel/Lumen applications with eloquent
What is UUID?
Universal Unique Identifier (UUID) is a 128-bit string used to uniquely identify objects/resources in computer systems. It also termed as Global Unique Identifier (GUID). The probability of duplicated UUID not zero, but close enough to be zero, to be negligible. We can use UUIDs in Laravel as primary key of records in our database.
Here we will look into implementing UUID as primary key in Laravel/Lumen applications.
Migration
First step to use UUID in our database is to set our table’s primary column type to specific type. Laravel migration sets primary key as ‘id’ of type Unsigned Integer
by default. i.e. $table->primary('id');
To use UUID, we will just set id
column type as uuid
. i.e. $table->uuid('id')
and set id column as primary column of our table $table->uuid('id')->primary()
, for every migration we have in our app.
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
Eloquent Model Events
Further, we will be using eloquent for easy database interaction. Now, in our model, we will generate UUID and set it to ID column, whenever any new record in inserted. For that, we will set a hook on model boot
method to listen to Eloquent creating
events.
class User extends Model
{
protected static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->{$user->getKeyName()} = (string) Str::uuid();
});
}
...
}
Eloquent auto increments primary key of models. In our case, as we are using UUID, we will have to disable auto incrementing. For that, we will set getIncrementing()
to false. And also, we will set to store IDs of table to save as string with getKeyType()
method.
public function getIncrementing()
{
return false;
}
public function getKeyType(){
return 'string';
}
So, out model will look something like this.
class User extends Model
{
protected static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->{$user->getKeyName()} = (string) Str::uuid();
});
}
public function getIncrementing()
{
return false;
}
public function getKeyType(){
return 'string';
}
}
That’s it. Now we are ready to UUIDs in our Laravel/Lumen app database.