Created
July 6, 2021 10:17
-
-
Save mathieutu/08ea153b52c4fb30944a16068a4dae2d to your computer and use it in GitHub Desktop.
uuid handling trait for eloquent models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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