Skip to content

Commit

Permalink
refactor: route model binding
Browse files Browse the repository at this point in the history
  • Loading branch information
bensherred committed Nov 25, 2023
1 parent a130f79 commit e472d26
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/HasSqids.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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);
}
}
18 changes: 18 additions & 0 deletions src/Mixins/WhereSqidMixin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace RedExplosion\Sqids\Mixins;

use Closure;
use Illuminate\Database\Eloquent\Builder;
use RedExplosion\Sqids\Sqids;

/** @mixin Builder */
class WhereSqidMixin
{
public function whereSqid(): Closure
{
return fn($id) => $this->whereKey(id: Sqids::decodeId(id: $id));
}
}
2 changes: 2 additions & 0 deletions src/SqidsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -32,5 +33,6 @@ public function boot(): void
protected function bootBuilderMixins(): void
{
Builder::mixin(new FindBySqidMixin());
Builder::mixin(new WhereSqidMixin());
}
}

0 comments on commit e472d26

Please sign in to comment.