Created
July 9, 2022 15:57
-
-
Save isu3ru/690c21dcc0d771b443978f227e2d9abd to your computer and use it in GitHub Desktop.
UUID as primary key in Laravel Eloquent Models
This file contains hidden or 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 | |
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