You Must Use UUID Instead of Auto-Incremented IDs in Laravel

Thoyib Hidayat
4 min readNov 7, 2023

In the world of web development, the choice between using auto-incremented numeric IDs or universally unique identifiers (UUIDs) as primary keys for database records is a topic that has garnered attention and discussion. In this article, we’ll explore the reasons why you should consider using UUIDs as primary keys in your Laravel applications, and we’ll refer to some valuable resources and articles for further insights.

What is a UUID?

A Universally Unique Identifier (UUID) is a 128-bit identifier that is guaranteed to be unique across all devices and all time. Unlike traditional auto-incremented IDs, UUIDs are not sequential numbers but rather random or pseudo-random values.

The Benefits of Using UUIDs in Laravel

1. Improved Data Security

UUIDs do not reveal the order or quantity of records in your database, providing an additional layer of data security. Auto-incremented IDs, on the other hand, can expose insights into your data structure, which may not be desirable.

2. Global Uniqueness

As the name suggests, UUIDs are universally unique. This means you can confidently combine data from different sources without worrying about ID conflicts. Whether you’re merging databases, working with distributed systems, or integrating third-party data, UUIDs simplify the process.

3. Reduced Collisions

Auto-incremented IDs are subject to collisions when multiple database servers generate records concurrently. UUIDs significantly reduce the likelihood of these collisions, as they are generated using a combination of timestamps, randomness, and other factors.

4. Data Integrity

UUIDs promote data integrity by reducing the risk of referential integrity issues. When records need to be merged or updated, UUIDs make it easier to match records between systems without creating conflicts or errors.

5. Support for Disconnected Systems

UUIDs are ideal for systems that operate in disconnected environments, such as mobile applications or distributed databases. Even without a centralized server to assign IDs, UUIDs ensure unique identifiers across all devices.

Building a laravel application using UUIDs

Step 1: Laravel Installation

If you don’t already have Laravel installed, you can set up a new Laravel project using Composer:

composer create-project — prefer-dist laravel/laravel laravel-uuid

Step 2: Database Configuration

Configure your database connection in the .env file as you would for any Laravel application.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

Step 3: Migration with UUIDs

Create a migration for your desired model and configure it to use UUIDs as the primary key. Since we already have a default migration file for the users table, we will make slight modifications to this file

public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

And we will slight modifications in User model

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Concerns\HasUuids;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasUuids;

protected $keyType = 'string'; // Set the key type to UUID
public $incrementing = false; // Disable auto-incrementing
/**
* The "booting" function of model
*
* @return void
*/
public static function boot() {
parent::boot();
// Auto generate UUID when creating data User
static::creating(function ($model) {
$model->id = Str::uuid();
});
}

/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];

/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];

/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

Step 5: Controller and Views

Create a controller and views as needed for your application. Implement your application logic as usual, utilizing the User model with UUIDs as primary keys.

References for Further Reading

To gain a deeper understanding of implementing UUIDs in Laravel and their benefits, you can explore the following articles:

  1. Educative: “How to Use UUIDs in Laravel”
  2. dev.to: “Implement UUID Primary Key in Laravel and Its Benefits

These resources provide detailed insights, practical examples, and Laravel-specific guidance for using UUIDs in your projects.

And you can visit my github repo for this article example code
https://github.com/thoyib-project/laravel-lab/tree/packages/uuid

Conclusion

While auto-incremented IDs have been the conventional choice for primary keys in databases, UUIDs offer unique advantages in terms of data security, global uniqueness, and data integrity. When considering the design of your next Laravel application, it’s worth exploring the benefits of UUIDs to enhance the performance, scalability, and security of your database. Embracing UUIDs in Laravel is a step towards building more robust and adaptable systems.

--

--

Thoyib Hidayat

I am a Software Engineer specializing in Back-End technology, Web Development.