Skip to content

Instantly share code, notes, and snippets.

@isu3ru
Created July 9, 2022 15:57
Show Gist options
  • Save isu3ru/690c21dcc0d771b443978f227e2d9abd to your computer and use it in GitHub Desktop.
Save isu3ru/690c21dcc0d771b443978f227e2d9abd to your computer and use it in GitHub Desktop.
UUID as primary key in Laravel Eloquent Models
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait UUIDable
{
/**
* Setup UUID as key
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
}
});
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return false;
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
return 'string';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment