Created
December 4, 2024 22:32
-
-
Save martinbean/709ec8b42d775e2823eed8c807e92292 to your computer and use it in GitHub Desktop.
Sqids trait for Eloquent models
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
<?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