Last active
September 9, 2015 19:39
-
-
Save dhanifudin/9757537 to your computer and use it in GitHub Desktop.
Eloquent Laravel Model that autogenerated uuid and save using binary format
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 | |
use Rhumsaa\Uuid\Uuid; | |
class UUIDModel extends Eloquent { | |
public $incrementing = false; | |
protected $softDelete = true; | |
public function __construct(array $attributes = array()) { | |
parent::__construct($attributes); | |
$this->setEventDispatcher(Capsule::getEventDispatcher()); | |
} | |
protected static function boot() { | |
parent::boot(); | |
static::creating(function($model) { | |
$model->{$model->getKeyName()} = (binary) $model->generateID(); | |
}); | |
} | |
public function generateID() { | |
return hex2bin(str_replace('-','',Uuid::uuid4())); | |
} | |
public function getID() { | |
return bin2hex($this->getAttribute($this->primaryKey)); | |
} | |
} |
@fwolf thanks for advice. sorry, I don't get notification for your comment.
It's just a small script when I learn laravel for first time, I will update it later.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a reminder, the model using UUID by creating event need Dispatcher instance set to them, like:
Without dispatcher instance set, even through the 'creating' event is fired, there are no listener to execute it, see https://github.com/laravel/framework/blob/master/src/Illuminate/Events/Dispatcher.php#L195