Created
February 4, 2022 03:05
-
-
Save vaibhavpandeyvpz/16e9afd43c3b0db05268ade1bea7587c to your computer and use it in GitHub Desktop.
Generate and use UUIDs as primary keys in Laravel
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 | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Str; | |
trait HasUuidAsPrimaryKey | |
{ | |
public static function bootHasUuidAsPrimaryKey() | |
{ | |
static::creating(function (Model $model) { | |
if (empty($model->{$model->getKeyName()})) { | |
$model->{$model->getKeyName()} = (string) Str::orderedUuid(); | |
} | |
}); | |
} | |
/** | |
* Get the value indicating whether the IDs are incrementing. | |
* | |
* @return bool | |
*/ | |
public function getIncrementing(): bool | |
{ | |
return false; | |
} | |
/** | |
* Get the auto-incrementing key type. | |
* | |
* @return string | |
*/ | |
public function getKeyType(): string | |
{ | |
return 'string'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment