Last active
December 13, 2019 19:44
-
-
Save chrisblackwell/83bb756f04164d89e52d21f521e3a4de to your computer and use it in GitHub Desktop.
UUID model trait for Laravel
This file contains hidden or 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 Ramsey\Uuid\Uuid; | |
trait UuidModel | |
{ | |
/** | |
* Hook into the boot method to catch creating and saving events | |
* | |
* @return void | |
*/ | |
public static function bootUuidModel() | |
{ | |
static::creating(function ($model) { | |
$model->{$model->getKeyName()} = Uuid::uuid4()->toString(); | |
}); | |
static::saving(function ($model) { | |
if ($model->{$model->getKeyName()} !== $model->getOriginal($model->getKeyName())) { | |
$model->{$model->getKeyName()} = $model->getOriginal($model->getKeyName()); | |
} | |
}); | |
} | |
/** | |
* Get the value indicating whether the IDs are incrementing. | |
* | |
* @return bool | |
*/ | |
public function getIncrementing() | |
{ | |
return false; | |
} | |
/** | |
* Get the auto-incrementing key type. | |
* | |
* @return string | |
*/ | |
public function getKeyType() | |
{ | |
return 'string'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment