-
-
Save oliuz/ff182e0b0a01d8dcbc810c49858b6424 to your computer and use it in GitHub Desktop.
A little trait to add to models that will have Uuids
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 | |
// 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