Skip to content

Instantly share code, notes, and snippets.

@martinbean
Created December 4, 2024 22:32
Show Gist options
  • Save martinbean/709ec8b42d775e2823eed8c807e92292 to your computer and use it in GitHub Desktop.
Save martinbean/709ec8b42d775e2823eed8c807e92292 to your computer and use it in GitHub Desktop.
Sqids trait for Eloquent models
<?php
namespace App\Models\Concerns;
use Sqids\Sqids;
/**
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait HasSqid
{
/**
* {@inheritDoc}
*/
public function resolveRouteBinding($value, $field = null)
{
if ($field === 'sqid') {
$ids = $this->getSqids()->decode($value);
if (empty($ids)) {
return null;
}
$field = null;
$value = $ids[0];
}
return parent::resolveRouteBinding($value, $field);
}
/**
* {@inheritDoc}
*/
public function resolveChildRouteBinding($childType, $value, $field)
{
if ($field === 'sqid') {
$ids = $this->getSqids()->decode($value);
if (empty($ids)) {
return null;
}
$field = null;
$value = $ids[0];
}
return parent::resolveChildRouteBinding($childType, $value, $field);
}
/**
* Get the Sqid attribute value for the model.
*/
public function getSqidAttribute(): string
{
return $this->getSqids()->encode([
$this->getKey(),
]);
}
/**
* Get an instance of the Sqids library.
*
* @return Sqids
*/
protected function getSqids(): Sqids
{
return new Sqids(
alphabet: $this->getSqidsAlphabet(),
minLength: $this->getSqidsMinLength(),
);
}
/**
* Get the Sqids alphabet to user for the model.
*/
protected function getSqidsAlphabet(): string
{
return Sqids::DEFAULT_ALPHABET;
}
/**
* Get the Sqids minimum length for the model.
*/
protected function getSqidsMinLength(): int
{
return Sqids::DEFAULT_MIN_LENGTH;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment