Skip to content

Instantly share code, notes, and snippets.

@renebakx
Created April 30, 2017 18:06
Show Gist options
  • Save renebakx/a0145b9f4f00735553201cc21101f744 to your computer and use it in GitHub Desktop.
Save renebakx/a0145b9f4f00735553201cc21101f744 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