Last active
November 6, 2019 22:08
-
-
Save robertdrakedennis/8db1e84d305aac0c2ba6a8c6ec92ba0b to your computer and use it in GitHub Desktop.
Simple Laravel UUID4 Generation on bootable models.
This file contains 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\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