PHP
Using UUIDs as Primary Keys in Laravel Eloquent Models
Learn how to configure Laravel Eloquent models to use Universally Unique Identifiers (UUIDs) instead of auto-incrementing integers as primary keys.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str; // Required for Str::uuid()
class Order extends Model
{
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The "type" of the primary key ID.
*
* @var string
*/
protected $keyType = 'string';
/**
* The "booted" method of the model.
*
* This is where we override the `creating` event to generate UUIDs.
*/
protected static function booted()
{
static::creating(function (Order $model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = (string) Str::uuid();
}
});
}
}
// Example usage:
// $order = Order::create(['total' => 123.45, 'customer_id' => 5]);
// echo $order->id; // Will output a UUID like 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
How it works: This snippet demonstrates how to configure a Laravel Eloquent model to use UUIDs (Universally Unique Identifiers) as primary keys instead of the default auto-incrementing integers. By setting `$incrementing` to `false` and `$keyType` to `string`, and then overriding the `creating` Eloquent event, we ensure that a new UUID is generated and assigned to the primary key attribute before the model is saved to the database. This is useful for distributed systems, preventing ID enumeration, and improving data merges.