Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Created February 4, 2022 03:05
Show Gist options
  • Save vaibhavpandeyvpz/16e9afd43c3b0db05268ade1bea7587c to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/16e9afd43c3b0db05268ade1bea7587c to your computer and use it in GitHub Desktop.
Generate and use UUIDs as primary keys in Laravel
<?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