-
-
Save scottmcclung/9a0882ddffe2c8a10a1de882d2d0d9f4 to your computer and use it in GitHub Desktop.
Trait for implementing UUIDs in Laravel 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 Ramsey\Uuid\Uuid; | |
| /** | |
| * Trait UuidPrimaryKey | |
| * @package App\Traits | |
| */ | |
| trait UuidPrimaryKey | |
| { | |
| /** | |
| * Binds creating/saving events to create UUIDs (and also prevent them from being overwritten). | |
| * | |
| * @return void | |
| */ | |
| public static function bootUuidPrimaryKey() | |
| { | |
| static::creating(function ($model) { | |
| // Don't let people provide their own UUIDs, we will generate a proper one. | |
| $model[$model->primaryKey] = Uuid::uuid1()->toString(); //using time based uuids | |
| }); | |
| static::saving(function ($model) { | |
| // Don't allow any updates to primary key | |
| $original_id = $model->getOriginal($model->primaryKey); | |
| if ($original_id !== $model[$model->primaryKey]) { | |
| $model[$model->primaryKey] = $original_id; | |
| } | |
| }); | |
| } | |
| } |
Author
Author
This gist forked from the work done by Dan Barrett. His blog on this is here: http://humaan.com/using-uuids-with-eloquent-in-laravel/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Install the UUID library: https://github.com/ramsey/uuid
composer require ramsey/uuid