Last active
January 20, 2016 18:08
-
-
Save sahibalejandro/276dbd4e91bc59e56d1a to your computer and use it in GitHub Desktop.
Uuid trait to use on eloquent models.
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
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