Skip to content

Instantly share code, notes, and snippets.

@dhanifudin
Last active September 9, 2015 19:39
Show Gist options
  • Save dhanifudin/9757537 to your computer and use it in GitHub Desktop.
Save dhanifudin/9757537 to your computer and use it in GitHub Desktop.
Eloquent Laravel Model that autogenerated uuid and save using binary format
<?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
Copy link

fwolf commented Apr 5, 2014

Just a reminder, the model using UUID by creating event need Dispatcher instance set to them, like:

public function __construct(array $attributes = array()) 
{
    parent::__construct($attributes);

    $this->setEventDispatcher(Capsule::getEventDispatcher());
}

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

@dhanifudin
Copy link
Author

@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