Created
December 10, 2015 04:08
-
-
Save danb-humaan/a7ecc24b87b11ff51ea0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Scope a query to only include models matching the supplied UUID. | |
* Returns the model by default, or supply a second flag `false` to get the Query Builder instance. | |
* | |
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException | |
* | |
* @param \Illuminate\Database\Schema\Builder $query The Query Builder instance. | |
* @param string $uuid The UUID of the model. | |
* @param bool|true $first Returns the model by default, or set to `false` to chain for query builder. | |
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder | |
*/ | |
public function scopeUuid($query, $uuid, $first = true) | |
{ | |
if (!is_string($uuid) || (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid) !== 1)) { | |
throw (new ModelNotFoundException)->setModel(get_class($this)); | |
} | |
$search = $query->where('uuid', $uuid); | |
return $first ? $search->firstOrFail() : $search; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment