Created
April 16, 2018 18:47
-
-
Save hopeseekr/751ab1b661077ca9ee80cba4d75212b9 to your computer and use it in GitHub Desktop.
A drop-dead simple UUID base model class for Laravel 5
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; | |
use Ramsey\Uuid\Uuid; | |
/** | |
* App\Models\UuidModel. | |
* | |
* @mixin \Eloquent | |
*/ | |
class UuidModel extends BaseModel | |
{ | |
/** @var bool Indicates if the IDs are auto-incrementing. */ | |
public $incrementing = false; | |
/** @var string The data-type of primary-key. */ | |
protected $keyType = 'string'; | |
/** | |
* Add an id to the model and save it in the database. | |
* | |
* @param array $options | |
* @return bool | |
*/ | |
public function save(array $options = []) | |
{ | |
if (empty($this->{$this->getKeyName()})) { | |
$this->{$this->getKeyName()} = self::generateNewId(); | |
} | |
return parent::save($options); | |
} | |
/** | |
* Get a new version 4 (random) UUID. | |
* | |
* @return string A 22 character Unique Identifier | |
*/ | |
public static function generateNewId(): string | |
{ | |
// 1. Generate the UUID. | |
$uuid = Uuid::uuid4(); | |
// 2. Strip the dashes. | |
$uuid = str_replace('-', '', $uuid); | |
// 3. Convert from hex to base62. | |
$uuid = gmp_strval(gmp_init(($uuid), 16), 62); | |
// We pad zeros to the beginning, as the result returned by gmp_strval after base conversion | |
// is not always 22 characters long. | |
$uuid = str_pad($uuid, 22, '0', STR_PAD_LEFT); | |
return $uuid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment