PHP
Using UUIDs or Custom Non-Incrementing Primary Keys with Eloquent
Configure Laravel Eloquent models to use custom primary keys like UUIDs instead of auto-incrementing integers for better scalability and distributed systems.
// app/Models/Order.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Order extends Model
{
/**
* The "type" of the primary key ID.
*
* @var string
*/
protected $keyType = 'string';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['total_amount'];
/**
* Boot the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = (string) Str::uuid();
}
});
}
}
// Example Usage
$order = App\Models\Order::create(['total_amount' => 199.99]);
echo $order->id; // Will output a UUID
How it works: By default, Eloquent assumes a primary key named `id` that is an auto-incrementing integer. To use UUIDs or other non-incrementing keys, you must set the `$incrementing` property to `false` and `$keyType` to `string`. The `boot` method with a `creating` event listener is a common pattern to automatically assign a UUID when a new model instance is being created, ensuring the ID is generated before it hits the database.