Skip to content

Instantly share code, notes, and snippets.

@janyksteenbeek
Created November 23, 2023 21:33
Show Gist options
  • Save janyksteenbeek/c461464247b5c1ff8a0c19cb2296c6a2 to your computer and use it in GitHub Desktop.
Save janyksteenbeek/c461464247b5c1ff8a0c19cb2296c6a2 to your computer and use it in GitHub Desktop.
App\Traits\HasUnids (Unique Name Identifier) trait for Laravel: create an ID based on first names.
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Str;
trait HasUnids
{
/**
* Initialize the trait.
*
* @return void
*/
public function initializeHasUnids()
{
$this->usesUniqueIds = true;
}
/**
* Get the columns that should receive a unique identifier.
*
* @return array
*/
public function uniqueIds()
{
return [$this->getKeyName()];
}
/**
* Generate a new UNID for the model.
*
* @return string
*/
public function newUniqueId()
{
return Str::slug(fake()->firstName() . '-' . fake()->firstName() . '-' . fake()->firstName() . '-' . fake()->firstName() . '-' . fake()->firstName() . '-' . fake()->firstName());
}
/**
* Retrieve the model for a bound value.
*
* @param Model|Relation $query
* @param mixed $value
* @param string|null $field
* @return Relation
*
* @throws ModelNotFoundException
*/
public function resolveRouteBindingQuery($query, $value, $field = null)
{
if ($field && in_array($field, $this->uniqueIds()) && !Str::isUlid($value)) {
throw (new ModelNotFoundException)->setModel(get_class($this), $value);
}
if (!$field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && !Str::isUlid($value)) {
throw (new ModelNotFoundException)->setModel(get_class($this), $value);
}
return parent::resolveRouteBindingQuery($query, $value, $field);
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
if (in_array($this->getKeyName(), $this->uniqueIds())) {
return 'string';
}
return $this->keyType;
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
if (in_array($this->getKeyName(), $this->uniqueIds())) {
return false;
}
return $this->incrementing;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment