Skip to content

Instantly share code, notes, and snippets.

@lkagan
Last active July 20, 2020 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lkagan/43cb241022663ae365d4f0e9ca28a3ad to your computer and use it in GitHub Desktop.
Save lkagan/43cb241022663ae365d4f0e9ca28a3ad to your computer and use it in GitHub Desktop.
UUID trait for Laravel / Eloquent
<?php
namespace App\Traits;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
trait HasUuid
{
/**
* Setup model for using UUID during creation and retrieval.
*/
public static function bootHasUuid(): void
{
self::creating(function (Model $model) {
$model->{$model->getKeyName()} = (string)Str::uuid();
});
self::retrieved(function (Model $model) {
$casts = [$model->getKeyName() => 'string'];
$model->casts = $model->casts ? array_merge($model->casts,
$casts) : $casts;
});
}
public function getIncrementing(): bool
{
return false;
}
public function getKeyType(): string
{
return 'string';
}
public function getRouteKeyName(): string
{
return 'uuid';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment