UUID in Laravel: A Simple Guide
Looking to upgrade from basic database auto-increment IDs? Consider UUID! In this easy-to-follow guide, let's dive into understanding UUID columns in Laravel and explore the various tools and methods.
Using UUID as Your Primary Key in Laravel
Laravel has made using UUIDs as primary keys a breeze since version v9.30. Here's a quick breakdown to get you started:
Swap out your usual ID creation with:
// Don't use: $table->id();
$table->uuid('id')->primary();
Add the Laravel-provided UUID trait:
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
use HasUuids;
}
Save your record with Eloquent, and a UUID will be auto-generated: