Skip to content

Commit

Permalink
use config file
Browse files Browse the repository at this point in the history
  • Loading branch information
EmadAdly committed Feb 16, 2017
1 parent afd2a16 commit 6cc1ff1
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/Uuids.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,45 @@
namespace Emadadly\LaravelUuid;

use Emadadly\LaravelUuid\UUIDManager;
use Illuminate\Database\Eloquent\ModelNotFoundException;

trait Uuids
{

/**
* Boot function from laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = UUIDManager::generate();
$model->{config('uuid.default_uuid_column')} = UUIDManager::generate();
});
static::saving(function ($model) {
$original_uuid = $model->getOriginal(config('uuid.default_uuid_column'));
if ($original_uuid !== $model->{config('uuid.default_uuid_column')}) {
$model->{config('uuid.default_uuid_column')} = $original_uuid;
}
});
}

/**
* Scope by uuid
* @param string uuid of the model.
*
*/
public function scopeUuid($query, $uuid, $first = true)
{
$match = preg_match('/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/', $uuid);

if (!is_string($uuid) || $match !== 1)
{
throw (new ModelNotFoundException)->setModel(get_class($this));
}

$results = $query->where(config('uuid.default_uuid_column'), $uuid);

return $first ? $results->firstOrFail() : $results;
}

}

0 comments on commit 6cc1ff1

Please sign in to comment.