Skip to content

Instantly share code, notes, and snippets.

@robertdrakedennis
Last active November 6, 2019 22:08
Show Gist options
  • Save robertdrakedennis/8db1e84d305aac0c2ba6a8c6ec92ba0b to your computer and use it in GitHub Desktop.
Save robertdrakedennis/8db1e84d305aac0c2ba6a8c6ec92ba0b to your computer and use it in GitHub Desktop.
Simple Laravel UUID4 Generation on bootable models.
<?php
namespace App\Traits\Models;
trait GeneratesUuid
{
/**
* Any model that is in the creating / bootable state will have a UUID 4 created for their primary key.
*
*/
protected static function bootGeneratesUuid(): void
{
static::creating(function ($model) {
$model->{$model->getKeyName()} = static::generateUUID();
});
}
/**
* Generates UUID4
*
* @return string
*/
public static function generateUUID(): string
{
return \Illuminate\Support\Str::orderedUuid()->toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment