Skip to content

Instantly share code, notes, and snippets.

@njugunagathere
Forked from renebakx/uuids.php
Created June 8, 2017 09:10
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 njugunagathere/f98b1b81aa3bb975b84cbface119f345 to your computer and use it in GitHub Desktop.
Save njugunagathere/f98b1b81aa3bb975b84cbface119f345 to your computer and use it in GitHub Desktop.
Laravel 5.4 UUID Trait
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Ramsey\Uuid\Uuid;
trait Uuids {
protected static function boot() {
parent::boot();
/**
* Add the UUID before persisting the model
*/
static::creating(function (Model $model) {
$uuidCol = config('app.default_uuid_column', 'uuid');
if (empty($model->attributes[$uuidCol])) {
$model->attributes[$uuidCol] = Uuid::uuid4();
}
});
}
/**
* Add UUID scope to model
* So you can query like Model::Uuid('uuid string');
* @param string Uuid
*
*/
public function scopeUuid($query, $uuid, $first = TRUE) {
if (!is_string($uuid) || !Uuid::isValid($uuid)) {
throw (new ModelNotFoundException)->setModel(get_class($this));
}
$results = $query->where(config('app.default_uuid_column', 'uuid'), $uuid);
return $first ? $results->firstOrFail() : $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment