Created
September 25, 2020 22:53
-
-
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
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 | |
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