Skip to content

Instantly share code, notes, and snippets.

@codyphobe
Forked from calebporzio/HasUuid.php
Created July 10, 2018 07:00
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 codyphobe/71afc6b11f3479bd82e2ad2ecc0a737f to your computer and use it in GitHub Desktop.
Save codyphobe/71afc6b11f3479bd82e2ad2ecc0a737f to your computer and use it in GitHub Desktop.
A little trait to add to models that will have Uuids
<?php
// Example usage in a model:
class ExampleModel extends Model
{
use HasUuid;
protected $primaryKey = 'uuid';
public $incrementing = false;
}
// The Trait:
trait HasUuid
{
public static function bootHasUuid()
{
static::creating(function ($model) {
if (! $model->{$model->getKeyName()}) {
$model->{$model->getKeyName()} = static::generateUuid();
}
});
}
public static function generateUuid()
{
return (string) Illuminate\Support\Str::uuid();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment