Skip to content

Instantly share code, notes, and snippets.

@scottmcclung
Forked from danb-humaan/UuidModel.php
Last active May 22, 2016 23:15
Show Gist options
  • Select an option

  • Save scottmcclung/9a0882ddffe2c8a10a1de882d2d0d9f4 to your computer and use it in GitHub Desktop.

Select an option

Save scottmcclung/9a0882ddffe2c8a10a1de882d2d0d9f4 to your computer and use it in GitHub Desktop.
Trait for implementing UUIDs in Laravel models
<?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;
}
});
}
}
@scottmcclung
Copy link
Author

Install the UUID library: https://github.com/ramsey/uuid

composer require ramsey/uuid

@scottmcclung
Copy link
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