diff --git a/src/HasSqids.php b/src/HasSqids.php index b5c3d05..8089400 100644 --- a/src/HasSqids.php +++ b/src/HasSqids.php @@ -4,7 +4,9 @@ namespace RedExplosion\Sqids; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\Relation; trait HasSqids { @@ -28,12 +30,29 @@ public function getRouteKeyName(): string * @param string|null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = null): ?Model + // public function resolveRouteBinding($value, $field = null): ?Model + // { + // if ($field !== null) { + // return parent::resolveRouteBinding(value: $value, field: $field); + // } + // + // return $this->findBySqid($value); + // } + + /** + * Retrieve the model for a bound value. + * + * @param Model|Relation $query + * @param mixed $value + * @param null $field + * @return Builder|Relation + */ + public function resolveRouteBindingQuery($query, $value, $field = null): Builder|Relation { - if ($field !== null) { - return parent::resolveRouteBinding(value: $value, field: $field); + if ($field && $field !== $this->getRouteKeyName()) { + return parent::resolveRouteBindingQuery(query: $query, value: $value, field: $field); } - return $this->findBySqid($value); + return $this->whereSqid($value); } } diff --git a/src/Mixins/WhereSqidMixin.php b/src/Mixins/WhereSqidMixin.php new file mode 100644 index 0000000..40222ec --- /dev/null +++ b/src/Mixins/WhereSqidMixin.php @@ -0,0 +1,18 @@ + $this->whereKey(id: Sqids::decodeId(id: $id)); + } +} diff --git a/src/SqidsServiceProvider.php b/src/SqidsServiceProvider.php index 436c34d..64e19a4 100644 --- a/src/SqidsServiceProvider.php +++ b/src/SqidsServiceProvider.php @@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\ServiceProvider; use RedExplosion\Sqids\Mixins\FindBySqidMixin; +use RedExplosion\Sqids\Mixins\WhereSqidMixin; class SqidsServiceProvider extends ServiceProvider { @@ -32,5 +33,6 @@ public function boot(): void protected function bootBuilderMixins(): void { Builder::mixin(new FindBySqidMixin()); + Builder::mixin(new WhereSqidMixin()); } }