Skip to content

Instantly share code, notes, and snippets.

@danb-humaan
Created December 10, 2015 06:26
Show Gist options
  • Save danb-humaan/a67b280e870cfeceadbe to your computer and use it in GitHub Desktop.
Save danb-humaan/a67b280e870cfeceadbe to your computer and use it in GitHub Desktop.
/**
* Scope a query to only include models matching the supplied ID or 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 scopeIdOrUuId($query, $id_or_uuid, $first = true)
{
if (!is_string($id_or_uuid) && !is_numeric($id_or_uuid)) {
throw (new ModelNotFoundException)->setModel(get_class($this));
}
if (preg_match('/^([0-9]+|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/', $id_or_uuid) !== 1) {
throw (new ModelNotFoundException)->setModel(get_class($this));
}
$search = $query->where(function ($query) use ($id_or_uuid) {
$query->where('id', $id_or_uuid)
->orWhere('uuid', $id_or_uuid);
});
return $first ? $search->firstOrFail() : $search;
}
@bhuvidya
Copy link

one possible enhancement could be to change the line

$query->where('id', $id_or_uuid)

to

$query->where($this->primaryKey, $id_or_uuid)

to cater for tables whose id field isn't called id

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment