Skip to content

Instantly share code, notes, and snippets.

@sahibalejandro
Last active January 20, 2016 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahibalejandro/276dbd4e91bc59e56d1a to your computer and use it in GitHub Desktop.
Save sahibalejandro/276dbd4e91bc59e56d1a to your computer and use it in GitHub Desktop.
Uuid trait to use on eloquent models.
namespace App\Eloquent;
use Ramsey\Uuid\Uuid;
trait UuidField
{
/**
* Add a uuid to the model before persist to the data base.
*
* @param array $options
*/
public function save(array $options = [])
{
if (!$this->exists) {
$this->uuid = Uuid::uuid4()->toString();
}
parent::save($options);
}
/**
* Get a record by its uuid.
*
* @param string $uuid
* @return $this|null
*/
public static function byUuid($uuid)
{
return static::where('uuid', '=', $uuid)->first();
}
/**
* Get the ID of a record based on his UUID.
*
* @param string $uuid
* @return int
*/
public static function idFromUuid($uuid)
{
if (!$model = static::byUuid($uuid)) {
return null;
}
return $model->id;
}
/**
* Scope to filter by uuid.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $uuid
*/
public function scopeUuid($query, $uuid)
{
$query->where('uuid', '=', $uuid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment