laravel-uuid maintained by centrex
UUID trait for Laravel Eloquent models
Auto-generates a UUID v4 on model creation, sets it as the route key, and provides a query scope for UUID lookups.
Installation
composer require centrex/laravel-uuid
Usage
1. Add the column to your migration
$table->uuid('uuid')->unique();
2. Add the trait to your model
use Centrex\LaravelUuid\HasUuid;
class Order extends Model
{
use HasUuid;
}
A UUID is automatically generated on creating if the uuid column is present and empty.
3. Route model binding
The trait overrides getRouteKeyName() to return 'uuid', so route model binding works out of the box:
// routes/web.php
Route::get('/orders/{order}', [OrderController::class, 'show']);
// URL: /orders/550e8400-e29b-41d4-a716-446655440000
4. Query scope
Order::uuid('550e8400-e29b-41d4-a716-446655440000')->first();
Custom column name
Override $uuid_column on the model or publish the config:
class Order extends Model
{
use HasUuid;
protected $uuid_column = 'public_id';
}
php artisan vendor:publish --tag="laravel-uuid-config"
Testing
composer test # full suite
composer test:unit # pest only
composer test:types # phpstan
composer lint # pint
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
License
The MIT License (MIT). Please see License File for more information.