Skip to content

Instantly share code, notes, and snippets.

@chrisblackwell
Last active December 13, 2019 19:44
Show Gist options
  • Save chrisblackwell/83bb756f04164d89e52d21f521e3a4de to your computer and use it in GitHub Desktop.
Save chrisblackwell/83bb756f04164d89e52d21f521e3a4de to your computer and use it in GitHub Desktop.
UUID model trait for Laravel
<?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