Skip to content

Instantly share code, notes, and snippets.

@mathieutu
Created July 6, 2021 10:17
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 mathieutu/08ea153b52c4fb30944a16068a4dae2d to your computer and use it in GitHub Desktop.
Save mathieutu/08ea153b52c4fb30944a16068a4dae2d to your computer and use it in GitHub Desktop.
uuid handling trait for eloquent models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Ramsey\Uuid\Uuid;
trait HasUuid
{
public static function bootHasUuid(): void
{
static::creating(function (Model $model) {
if (empty($model->attributes['id'])) {
$model->attributes['id'] = (string) Str::orderedUuid();
}
});
}
public function setIdAttribute(?string $id): void
{
if (!$this->exists && is_string($id) && Uuid::isValid($id)) {
$this->attributes['id'] = $id;
}
}
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'uuid';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment