Last active
July 20, 2020 23:32
-
-
Save lkagan/43cb241022663ae365d4f0e9ca28a3ad to your computer and use it in GitHub Desktop.
UUID trait for Laravel / Eloquent
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\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