Skip to content

Instantly share code, notes, and snippets.

@tanthammar
Last active January 28, 2021 16:47
Show Gist options
  • Save tanthammar/8c6fba89ae09a730fc7fe93cf375b03a to your computer and use it in GitHub Desktop.
Save tanthammar/8c6fba89ae09a730fc7fe93cf375b03a to your computer and use it in GitHub Desktop.
Laravel Model Uuid trait
<?php
namespace App\Traits;
use Hidehalo\Nanoid\Client;
/**
* Source: https://github.com/jamesmills/eloquent-uuid
* added prefix
* last updated 28 jan 2021.
*/
trait HasUuidTrait
{
public function initializeHasUuidTrait()
{
$this->uuid = self::generate_uuid($this);
}
protected static function bootHasUuidTrait()
{
static::creating(function ($model) {
if (!$model->uuid) {
$model->uuid = self::generate_uuid($model);
}
});
}
protected static function generate_uuid($model)
{
$client = new Client();
$uuid = $client->generateId(21);
$prefix = $model::UUID_PREFIX ?? false;
if ($prefix) {
$uuid = (string) $prefix . $uuid;
} else {
$uuid = (string) $uuid;
}
return $uuid;
}
public static function findByUuidOrFail($uuid)
{
return self::whereUuid($uuid)->firstOrFail();
}
public static function findByUuid($uuid)
{
return self::whereUuid($uuid)->first();
}
public static function getIdFromUuid($uuid): int
{
return self::whereUuid($uuid)->pluck('id')->first();
}
/**
* Eloquent scope to look for a given UUID.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $uuid The UUID to search for
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithUuid($query, $uuid)
{
return $query->where('uuid', $uuid);
}
/**
* Eloquent scope to look for multiple given UUIDs.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $uuids The UUIDs to search for
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithUuids($query, array $uuids)
{
return $query->whereIn('uuid', $uuids);
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'uuid';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment