Skip to content

Instantly share code, notes, and snippets.

@dallin
Created September 25, 2020 22:53
Show Gist options
  • Save dallin/5d8ac6851b7e03b760d924efe755c943 to your computer and use it in GitHub Desktop.
Save dallin/5d8ac6851b7e03b760d924efe755c943 to your computer and use it in GitHub Desktop.
Trait for Laravel Eloquent models to use a UUID as their primary key
<?php
namespace App\Models\Concerns;
use Illuminate\Support\Str;
/**
* Model has a UUID primary key.
*/
trait HasUuidPrimaryKey
{
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
}
});
}
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'uuid';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment