Skip to content

Instantly share code, notes, and snippets.

@finagin
Last active December 19, 2020 23:11
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 finagin/6181bdd3994de93e39d7a6d4157f67b3 to your computer and use it in GitHub Desktop.
Save finagin/6181bdd3994de93e39d7a6d4157f67b3 to your computer and use it in GitHub Desktop.
Laravel Eloquent uses UUID
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait UsesUuid
{
/**
* Boot the UUID trait for a model.
*
* @return void
*/
protected static function bootUsesUuid()
{
static::creating(function ($model) {
if (! $model->getKey()) {
$model->setAttribute(
$model->getKeyName(),
Str::orderedUuid(),
);
}
});
}
/**
* Initialize the UUID trait for an instance.
*
* @return void
*/
public function initializeUsesUuid()
{
$this
->setKeyName('uuid')
->setKeyType('string')
->setIncrementing(false)
->mergeCasts([$this->getKeyName() => $this->getKeyType()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment