Skip to content

[12.x] Adds resolver for specific Model route binding fields #55646

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -178,6 +179,13 @@ abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToSt
*/
protected static $ignoreOnTouch = [];

/**
* The array of field resolvers on the model.
*
* @var array<class-string<\Illuminate\Database\Eloquent\Model>, (callable(mixed, string, \Illuminate\Database\Eloquent\Builder<static>):mixed)>
*/
protected static $fieldResolvers = [];

/**
* Indicates whether lazy loading should be restricted on all models.
*
Expand Down Expand Up @@ -2230,7 +2238,20 @@ protected function childRouteBindingRelationshipName($childType)
*/
public function resolveRouteBindingQuery($query, $value, $field = null)
{
return $query->where($field ?? $this->getRouteKeyName(), $value);
$field ??= $this->getRouteKeyName();

if ($callback = static::$fieldResolvers[static::class][$field] ?? null) {
$result = $callback($value, $field, $query);

return match (true) {
$result instanceof Builder,
$result instanceof QueryBuilder => $result,
$result === null => $query,
default => $query->where($field, $result),
};
}

return $query->where($field, $value);
}

/**
Expand Down Expand Up @@ -2286,6 +2307,18 @@ public static function isAutomaticallyEagerLoadingRelationships()
return static::$modelsShouldAutomaticallyEagerLoadRelationships;
}

/**
* Register a field resolver for the current Model.
*
* @param string $field
* @param (callable(mixed, string, \Illuminate\Database\Eloquent\Builder):mixed)|null $callback
* @return void
*/
public static function resolveField($field, ?callable $callback)
{
static::$fieldResolvers[static::class][$field] = $callback;
}

/**
* Determine if discarding guarded attribute fills is disabled.
*
Expand Down
64 changes: 64 additions & 0 deletions tests/Routing/RoutingRouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Illuminate\Container\Container;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Events\Dispatcher;
Expand All @@ -39,6 +40,7 @@
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Str;
use LogicException;
use Mockery;
use PHPUnit\Framework\TestCase;
use stdClass;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
Expand All @@ -49,6 +51,11 @@

class RoutingRouteTest extends TestCase
{
protected function setUp(): void
{
RoutingTestUserModel::resolveField('test_field', null);
}

public function testBasicDispatchingOfRoutes()
{
$router = $this->getRouter();
Expand Down Expand Up @@ -1971,6 +1978,63 @@ public function testImplicitBindingsWithMissingModelHandledByMissingOnGroupLevel
$this->assertEquals(302, $response->getStatusCode());
}

public function testImplicitBindingsWithCustomFieldResolver()
{
RoutingTestUserModel::resolveField('test_field', function ($value, $field, $query) {
$this->assertSame('something-else', $value);
$this->assertSame('test_field', $field);
$this->assertInstanceOf(RoutingTestUserModel::class, $query);

return 'taylor';
});

$router = $this->getRouter();
$router->get('foo/{bar:test_field}', [
'middleware' => SubstituteBindings::class,
'uses' => function (?RoutingTestUserModel $bar = null) {
$this->assertInstanceOf(RoutingTestUserModel::class, $bar);

return $bar->first();
},
]);

$request = Request::create('foo/something-else', 'GET');

$response = $router->dispatch($request);
$this->assertEquals(200, $response->getStatusCode());
}

public function testImplicitBindingsWithCustomFieldResolverHijacksQuery()
{
$mockQuery = Mockery::mock(Builder::class);
$mockQuery->expects('where')->with('foo', 'bar')->andReturnSelf();
$mockQuery->expects('first')->andReturn((new RoutingTestUserModel)->forceFill(['value' => 'taylor']));

RoutingTestUserModel::resolveField('test_field', function ($value, $field, $query) use ($mockQuery) {
$this->assertSame('something-else', $value);
$this->assertSame('test_field', $field);
$this->assertInstanceOf(RoutingTestUserModel::class, $query);

return $mockQuery->where('foo', 'bar');
});

$router = $this->getRouter();
$router->get('foo/{bar:test_field}', [
'middleware' => SubstituteBindings::class,
'uses' => function (?RoutingTestUserModel $bar = null) {
$this->assertInstanceOf(RoutingTestUserModel::class, $bar);
$this->assertSame('taylor', $bar->value);

return $bar;
},
]);

$request = Request::create('foo/something-else', 'GET');

$response = $router->dispatch($request);
$this->assertEquals(200, $response->getStatusCode());
}

public function testImplicitBindingsWithOptionalParameterWithNoKeyInUri()
{
$router = $this->getRouter();
Expand Down